redis/client.go

66 lines
1.5 KiB
Go
Raw Normal View History

2022-06-15 11:50:17 +08:00
// Package redis ...
//
// Description : redis 客户端
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-02-27 4:49 下午
package redis
import (
2024-06-19 10:24:51 +08:00
"git.zhangdeman.cn/zhangdeman/redis/abstract"
"github.com/pkg/errors"
redisClient "github.com/redis/go-redis/v9"
2022-06-15 11:50:17 +08:00
"go.uber.org/zap"
2024-06-19 10:24:51 +08:00
"sync"
2022-06-15 11:50:17 +08:00
)
2024-06-19 10:24:51 +08:00
var Client abstract.IRedisClient
2022-06-22 21:34:16 +08:00
2024-06-19 10:24:51 +08:00
func init() {
Client = &OwnClient{
lock: &sync.RWMutex{},
instanceTable: make(map[string]*redisClient.ClusterClient),
2022-06-22 21:34:16 +08:00
}
2022-06-15 15:02:45 +08:00
}
type OwnClient struct {
2024-06-19 10:24:51 +08:00
lock *sync.RWMutex
instanceTable map[string]*redisClient.ClusterClient
logger *zap.Logger
2022-06-15 15:02:45 +08:00
}
2024-06-19 10:24:51 +08:00
func (o *OwnClient) GetRealClient(instanceFlag string) *redisClient.ClusterClient {
o.lock.RLock()
defer o.lock.RUnlock()
return o.instanceTable[instanceFlag]
2022-06-15 11:50:17 +08:00
}
2024-06-19 10:24:51 +08:00
func (o *OwnClient) GetRealClientWithError(instanceFlag string) (*redisClient.ClusterClient, error) {
o.lock.RLock()
defer o.lock.RUnlock()
instance, exist := o.instanceTable[instanceFlag]
2022-06-15 11:50:17 +08:00
if !exist {
2024-06-19 10:24:51 +08:00
return nil, errors.New(instanceFlag + " : redis instance is not found")
2022-06-15 11:50:17 +08:00
}
2024-06-19 10:24:51 +08:00
return instance, nil
2022-06-15 11:50:17 +08:00
}
2024-06-19 10:24:51 +08:00
func (o *OwnClient) AddClient(instanceFlag string, instanceConfig *redisClient.ClusterOptions) error {
instance := redisClient.NewClusterClient(instanceConfig)
o.lock.Lock()
defer o.lock.Unlock()
o.instanceTable[instanceFlag] = instance
return nil
2022-06-15 11:50:17 +08:00
}
2024-06-19 10:24:51 +08:00
func (o *OwnClient) RemoveClient(instanceFlag string) {
o.lock.Lock()
defer o.lock.Unlock()
delete(o.instanceTable, instanceFlag)
2023-08-16 11:55:04 +08:00
}
2024-06-19 10:24:51 +08:00
func (o *OwnClient) SetLogger(loggerInstance *zap.Logger) {
o.logger = loggerInstance
2022-06-15 11:50:17 +08:00
}