代码拉取完成,页面将自动刷新
package hwf
import (
"context"
"fmt"
"sync"
"time"
"github.com/redis/go-redis/v9"
)
// redisConfig defines Redis connection configuration
type redisConfig struct {
Addr string `ini:"addr"` // Redis地址,如 127.0.0.1:6379
Password string `ini:"password"` // Redis密码
DB int `ini:"db"` // Redis数据库索引
PoolSize int `ini:"pool_size"` // 连接池大小
}
var defaultRedis *redis.Client
var namedRedis = map[string]*redis.Client{}
var redisMu sync.RWMutex
// setupRedis initializes the default Redis client with the given config.
func setupRedis(cfg redisConfig) error {
if cfg.Addr == "" {
// 未配置Redis,跳过初始化
return nil
}
client, err := openRedis(cfg)
if err != nil {
return err
}
defaultRedis = client
return nil
}
// setupNamedRedis initializes a named Redis client.
func setupNamedRedis(name string, cfg redisConfig) error {
if cfg.Addr == "" {
return nil
}
client, err := openRedis(cfg)
if err != nil {
return err
}
redisMu.Lock()
namedRedis[name] = client
redisMu.Unlock()
return nil
}
// openRedis creates a new Redis client and tests the connection.
func openRedis(cfg redisConfig) (*redis.Client, error) {
poolSize := cfg.PoolSize
if poolSize <= 0 {
poolSize = 10 // default pool size
}
client := redis.NewClient(&redis.Options{
Addr: cfg.Addr,
Password: cfg.Password,
DB: cfg.DB,
PoolSize: poolSize,
})
// Test connection with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := client.Ping(ctx).Err(); err != nil {
return nil, fmt.Errorf("redis connection failed: %w", err)
}
return client, nil
}
// GetRedis returns the default Redis client.
// Returns nil if Redis is not configured or initialization failed.
func GetRedis() *redis.Client {
return defaultRedis
}
// GetNamedRedis returns a named Redis client by name (e.g., "001", "002").
// Returns nil if the named Redis is not configured.
func GetNamedRedis(name string) *redis.Client {
redisMu.RLock()
defer redisMu.RUnlock()
return namedRedis[name]
}
// closeAllRedis closes all Redis connections (called on shutdown).
func CloseAllRedis() {
if defaultRedis != nil {
_ = defaultRedis.Close()
}
redisMu.Lock()
for _, client := range namedRedis {
if client != nil {
_ = client.Close()
}
}
namedRedis = map[string]*redis.Client{}
redisMu.Unlock()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。