1 Star 0 Fork 0

sun/common_pkg

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
goredis.go 3.34 KB
一键复制 编辑 原始数据 按行查看 历史
yzsunjianguo 提交于 2023-09-22 00:18 +08:00 . 注释
// Package goredis is a library wrapped on top of github.com/go-redis/redis.
package goredis
import (
"strings"
"github.com/go-redis/redis/extra/redisotel"
"github.com/go-redis/redis/v8"
)
const (
// ErrRedisNotFound not exist in redis
ErrRedisNotFound = redis.Nil
// DefaultRedisName default redis name
DefaultRedisName = "default"
)
// Init connecting to redis
// dsn supported formats.
// no password, no db: localhost:6379
// with password and db: <user>:<pass>@localhost:6379/2
func Init(dsn string, opts ...Option) (*redis.Client, error) {
o := defaultOptions()
o.apply(opts...)
opt, err := getRedisOpt(dsn, o)
if err != nil {
return nil, err
}
rdb := redis.NewClient(opt)
if o.enableTrace { // tracing is enabled or not depending on the setting
rdb.AddHook(redisotel.TracingHook{})
}
return rdb, nil
}
func getRedisOpt(dsn string, opts *options) (*redis.Options, error) {
if len(dsn) > 8 {
if !strings.Contains(dsn[len(dsn)-3:], "/") {
dsn += "/0" // use db 0 by default
}
if dsn[:8] != "redis://" {
dsn = "redis://" + dsn
}
}
redisOpts, err := redis.ParseURL(dsn)
if err != nil {
return nil, err
}
if opts.dialTimeout > 0 {
redisOpts.DialTimeout = opts.dialTimeout
}
if opts.readTimeout > 0 {
redisOpts.ReadTimeout = opts.readTimeout
}
if opts.writeTimeout > 0 {
redisOpts.WriteTimeout = opts.writeTimeout
}
return redisOpts, nil
}
// Init2 connecting to redis
func Init2(addr string, password string, db int, opts ...Option) *redis.Client {
o := defaultOptions()
o.apply(opts...)
rdb := redis.NewClient(&redis.Options{
Addr: addr,
Password: password,
DB: db,
////连接池容量及闲置连接数量
//PoolSize: 15, // 连接池最大socket连接数,默认为4倍CPU数, 4 * runtime.NumCPU
//MinIdleConns: 10, //在启动阶段创建指定数量的Idle连接,并长期维持idle状态的连接数不少于指定数量;。
//超时
DialTimeout: o.dialTimeout, //连接建立超时时间,默认5秒。
ReadTimeout: o.readTimeout, //读超时,默认3秒, -1表示取消读超时
WriteTimeout: o.writeTimeout, //写超时,默认等于读超时
//PoolTimeout: o.readTimeout + 1, //当所有连接都处在繁忙状态时,客户端等待可用连接的最大等待时长,默认为读超时+1秒
//
////闲置连接检查包括IdleTimeout,MaxConnAge
//IdleCheckFrequency: 60 * time.Second, //闲置连接检查的周期,默认为1分钟,-1表示不做周期性检查,只在客户端获取连接时对闲置连接进行处理。
//IdleTimeout: 5 * time.Minute, //闲置超时,默认5分钟,-1表示取消闲置超时检查
//MaxConnAge: 0 * time.Second, //连接存活时长,从创建开始计时,超过指定时长则关闭连接,默认为0,即不关闭存活时长较长的连接
//
////命令执行失败时的重试策略
//MaxRetries: 0, // 命令执行失败时,最多重试多少次,默认为0即不重试
//MinRetryBackoff: 8 * time.Millisecond, //每次计算重试间隔时间的下限,默认8毫秒,-1表示取消间隔
//MaxRetryBackoff: 512 * time.Millisecond, //每次计算重试间隔时间的上限,默认512毫秒,-1表示取消间隔
})
if o.enableTrace { // tracing is enabled or not depending on the setting
rdb.AddHook(redisotel.TracingHook{})
}
return rdb
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/jianguosun_admin/common_pkg.git
git@gitee.com:jianguosun_admin/common_pkg.git
jianguosun_admin
common_pkg
common_pkg
v1.0.4

搜索帮助