81 lines
2.1 KiB
Go
81 lines
2.1 KiB
Go
package redisx
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
|
|
redis "github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// PoolSize:连接池中的最大连接数。
|
|
// MinIdleConns:连接池中的最少空闲连接数。
|
|
// MaxConnAge:连接池中连接的最长寿命。
|
|
// PoolTimeout:当所有连接都被使用时,客户端等待一个连接被释放到连接池的最长时间。
|
|
// IdleTimeout:在连接池中保持空闲状态的最长时间,超过这个时间的空闲连接将被关闭。
|
|
// IdleCheckFrequency:检查空闲连接的频率。
|
|
|
|
// 单机
|
|
func NewRedis(ctx context.Context, opts ...Option) redis.UniversalClient {
|
|
opt := defaultOptions()
|
|
for _, apply := range opts {
|
|
apply(&opt)
|
|
}
|
|
|
|
var tlsConfig *tls.Config
|
|
if opt.enableTLS {
|
|
tlsConfig = &tls.Config{InsecureSkipVerify: true}
|
|
}
|
|
|
|
var client redis.UniversalClient
|
|
|
|
switch opt.mode {
|
|
case RedisModeCluster:
|
|
// 集群模式
|
|
if len(opt.address) == 0 {
|
|
panic("redis cluster mode requires at least one address")
|
|
}
|
|
client = redis.NewClusterClient(
|
|
&redis.ClusterOptions{
|
|
Addrs: opt.address,
|
|
Password: opt.password, // no password set
|
|
TLSConfig: tlsConfig,
|
|
},
|
|
)
|
|
case RedisModeSentinel:
|
|
// 哨兵模式
|
|
if len(opt.sentinels) == 0 {
|
|
panic("redis sentinel mode requires at least one sentinel address")
|
|
}
|
|
client = redis.NewFailoverClient(
|
|
&redis.FailoverOptions{
|
|
MasterName: opt.masterName,
|
|
SentinelAddrs: opt.sentinels,
|
|
Password: opt.password, // no password set
|
|
TLSConfig: tlsConfig,
|
|
DB: opt.db, // use default DB
|
|
// SentinelPassword: global.Config.Redis.Password, // 哨兵认证密码(如果有)
|
|
// SentinelUsername: global.Config.Redis.Username, // 哨兵认证用户名(如果有)
|
|
},
|
|
)
|
|
default:
|
|
// 单机模式
|
|
if len(opt.address) == 0 {
|
|
panic("redis single mode requires an address")
|
|
}
|
|
client = redis.NewClient(
|
|
&redis.Options{
|
|
Addr: opt.address[0],
|
|
Password: opt.password, // no password set
|
|
DB: opt.db, // use default DB
|
|
TLSConfig: tlsConfig,
|
|
},
|
|
)
|
|
}
|
|
|
|
_, err := client.Ping(ctx).Result()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return client
|
|
}
|