1 Star 0 Fork 0

hwfo/hwf

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
redis.go 2.37 KB
一键复制 编辑 原始数据 按行查看 历史
haitgo 提交于 2025-12-27 17:04 +08:00 . 完善token中间件功能
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()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/hwfo/hwf.git
git@gitee.com:hwfo/hwf.git
hwfo
hwf
hwf
v1.0.2

搜索帮助