- redis增加url连接

master
dtapps 2 months ago
parent b99cbca10a
commit 0ed080ee44

@ -13,5 +13,5 @@
#### 安装 #### 安装
```shell ```shell
go get -v -u go.dtapp.net/dorm@v1.0.57 go get -v -u go.dtapp.net/dorm@v1.0.58
``` ```

@ -22,29 +22,29 @@ type RedisClientConfig struct {
// RedisClient // RedisClient
// https://redis.uptrace.dev/ // https://redis.uptrace.dev/
type RedisClient struct { type RedisClient struct {
db *redis.Client // 驱动 db *redis.Client // 驱动
config *RedisClientConfig // 配置
} }
// NewRedisClient 创建实例
func NewRedisClient(config *RedisClientConfig) (*RedisClient, error) { func NewRedisClient(config *RedisClientConfig) (*RedisClient, error) {
c := &RedisClient{} c := &RedisClient{}
c.config = config if config.PoolSize == 0 {
if c.config.PoolSize == 0 { config.PoolSize = 100
c.config.PoolSize = 100
} }
c.db = redis.NewClient(&redis.Options{ c.db = redis.NewClient(&redis.Options{
Addr: c.config.Addr, // 地址 Addr: config.Addr, // 地址
Password: c.config.Password, // 密码 Password: config.Password, // 密码
DB: c.config.DB, // 数据库 DB: config.DB, // 数据库
PoolSize: c.config.PoolSize, // 连接池大小 PoolSize: config.PoolSize, // 连接池大小
ReadTimeout: c.config.ReadTimeout, // 读取超时 ReadTimeout: config.ReadTimeout, // 读取超时
}) })
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() defer cancel()
// 检测 Redis 连接是否正常连接
_, err := c.db.Ping(ctx).Result() _, err := c.db.Ping(ctx).Result()
if err != nil { if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
@ -52,3 +52,28 @@ func NewRedisClient(config *RedisClientConfig) (*RedisClient, error) {
return c, nil 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
}

@ -1,4 +1,4 @@
package dorm package dorm
// Version 版本 // Version 版本
const Version = "1.0.57" const Version = "1.0.58"

Loading…
Cancel
Save