106 lines
2.3 KiB
Go
106 lines
2.3 KiB
Go
package redisClient
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/go-redis/redis/v8"
|
|
"sync"
|
|
)
|
|
|
|
// 保持向后兼容的全局客户端
|
|
var Client *redis.Client
|
|
|
|
// 连接管理器,用于管理多个 Redis 连接
|
|
var (
|
|
clients = make(map[string]*redis.Client)
|
|
clientsMux sync.RWMutex
|
|
)
|
|
|
|
// InitRedis 初始化默认 Redis 客户端(保持向后兼容)
|
|
func InitRedis(addr, password string, db int) {
|
|
Client = redis.NewClient(&redis.Options{
|
|
Addr: addr,
|
|
Password: password,
|
|
DB: db,
|
|
})
|
|
// 同时将默认客户端添加到连接管理器
|
|
clientsMux.Lock()
|
|
clients["default"] = Client
|
|
clientsMux.Unlock()
|
|
}
|
|
|
|
// GetClient 获取默认 Redis 客户端(保持向后兼容)
|
|
func GetClient() *redis.Client {
|
|
return Client
|
|
}
|
|
|
|
// CloseRedis 关闭默认 Redis 客户端(保持向后兼容)
|
|
func CloseRedis() error {
|
|
if Client != nil {
|
|
return Client.Close()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// AddClient 添加一个新的 Redis 客户端
|
|
func AddClient(name, addr, password string, db int) {
|
|
client := redis.NewClient(&redis.Options{
|
|
Addr: addr,
|
|
Password: password,
|
|
DB: db,
|
|
})
|
|
clientsMux.Lock()
|
|
clients[name] = client
|
|
clientsMux.Unlock()
|
|
}
|
|
|
|
// GetClientByName 根据名称获取 Redis 客户端
|
|
func GetClientByName(name string) (*redis.Client, error) {
|
|
clientsMux.RLock()
|
|
defer clientsMux.RUnlock()
|
|
client, ok := clients[name]
|
|
if !ok {
|
|
return nil, errors.New("redis client not found: " + name)
|
|
}
|
|
return client, nil
|
|
}
|
|
|
|
// CloseClient 关闭指定名称的 Redis 客户端
|
|
func CloseClient(name string) error {
|
|
clientsMux.Lock()
|
|
defer clientsMux.Unlock()
|
|
client, ok := clients[name]
|
|
if !ok {
|
|
return errors.New("redis client not found: " + name)
|
|
}
|
|
err := client.Close()
|
|
if err == nil {
|
|
delete(clients, name)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// CloseAllClients 关闭所有 Redis 客户端
|
|
func CloseAllClients() error {
|
|
clientsMux.Lock()
|
|
defer clientsMux.Unlock()
|
|
var lastErr error
|
|
for name, client := range clients {
|
|
if err := client.Close(); err != nil {
|
|
lastErr = err
|
|
}
|
|
delete(clients, name)
|
|
}
|
|
return lastErr
|
|
}
|
|
|
|
// ListClients 列出所有可用的 Redis 客户端名称
|
|
func ListClients() []string {
|
|
clientsMux.RLock()
|
|
defer clientsMux.RUnlock()
|
|
names := make([]string, 0, len(clients))
|
|
for name := range clients {
|
|
names = append(names, name)
|
|
}
|
|
return names
|
|
}
|