You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
dorm/redis.go

80 lines
1.7 KiB

2 years ago
package dorm
import (
"context"
"errors"
"fmt"
4 months ago
"github.com/redis/go-redis/v9"
2 years ago
"time"
)
2 years ago
// RedisClientFun *RedisClient 驱动
type RedisClientFun func() *RedisClient
2 years ago
type RedisClientConfig struct {
Addr string // 地址
Password string // 密码
DB int // 数据库
PoolSize int // 连接池大小
ReadTimeout time.Duration // 读取超时
2 years ago
}
2 years ago
// RedisClient
// https://redis.uptrace.dev/
2 years ago
type RedisClient struct {
db *redis.Client // 驱动
2 years ago
}
// NewRedisClient 创建实例
2 years ago
func NewRedisClient(config *RedisClientConfig) (*RedisClient, error) {
2 years ago
c := &RedisClient{}
if config.PoolSize == 0 {
config.PoolSize = 100
2 years ago
}
4 months ago
c.db = redis.NewClient(&redis.Options{
Addr: config.Addr, // 地址
Password: config.Password, // 密码
DB: config.DB, // 数据库
PoolSize: config.PoolSize, // 连接池大小
ReadTimeout: config.ReadTimeout, // 读取超时
2 years ago
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 检测 Redis 连接是否正常连接
4 months ago
_, err := c.db.Ping(ctx).Result()
2 years ago
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
return c, nil
}
// NewRedisClientURL 创建实例
func NewRedisClientURL(redisURL string) (*RedisClient, error) {
c := &RedisClient{}
opt, err := redis.ParseURL(redisURL)
if err != nil {
return c, nil
}
// 创建 Redis 客户端
c.db = redis.NewClient(opt)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 检测 Redis 连接是否正常连接
_, err = c.db.Ping(ctx).Result()
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
return c, nil
}