1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
redis.go 1.84 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2024-01-07 12:07 . 注删配置
package redis
import (
"context"
commonconfig "gitee.com/h79/goutils/common/config"
"gitee.com/h79/goutils/common/result"
"gitee.com/h79/goutils/dao/config"
"gitee.com/h79/goutils/dao/option"
"github.com/go-redis/redis/v8"
"go.uber.org/zap"
)
var _ Client = (*Connector)(nil)
type Connector struct {
selectName string
clientMap map[string]*Adapter
}
func NewRedis(conf []config.Redis, opts ...option.Option) (Client, error) {
zap.L().Info("Redis", zap.Any("Config", conf))
clients := &Connector{clientMap: map[string]*Adapter{}}
for i := range conf {
adapter, err := NewAdapter(conf[i].Name, &conf[i].Master, &conf[i].Sentinel, &conf[i].Cluster, opts...)
if err != nil {
continue
}
clients.clientMap[conf[i].Name] = adapter
}
if len(clients.clientMap) > 0 && len(conf) > 0 && conf[0].Logger.LogLevel > 0 {
log := &Logger{
RedisLogger: conf[0].Logger,
}
redis.SetLogger(log)
if commonconfig.RegisterConfig != nil {
commonconfig.RegisterConfig("Redis|"+conf[0].Name, log.handlerConfig)
}
}
return clients, nil
}
func (c *Connector) Get(name string) (Redis, error) {
if len(name) == 0 {
name = c.selectName
}
cli, exists := c.clientMap[name]
if exists == true {
return cli, nil
}
return nil, result.Error(result.ErrNotFound, "Not found")
}
func (c *Connector) Close(name string) error {
if len(name) == 0 {
name = c.selectName
}
cli, exists := c.clientMap[name]
if exists == true {
return cli.client.Close()
}
return nil
}
func (c *Connector) CloseAll() {
for _, cli := range c.clientMap {
_ = cli.client.Close()
}
c.clientMap = nil
}
func (c *Connector) Select(name string) {
c.selectName = name
}
func (c *Connector) SelectDB(name string, index int) error {
cli, err := c.Get(name)
if err != nil {
return err
}
_, err = cli.Rds().Do(context.Background(), "select", index).Result()
return err
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.19

搜索帮助