- 新增 go-redis/v9 依赖 - 新增 config.yaml redis 配置段 + RedisConfig 结构体 + REDIS_PASSWORD 环境变量覆盖 - 新增 common/redis.go Redis 客户端初始化 - 完整实现 session/redis_store.go,实现 Store 接口全部 7 个方法 - Redis TTL 自动过期,无须后台清理 goroutine - deps_core.go 根据 cfg.Redis.Enabled 自动选择 RedisStore/MemoryStore - router.go + main.go 透传 redisClient 参数
29 lines
619 B
Go
29 lines
619 B
Go
package common
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
"metazone.cc/metalab/internal/config"
|
|
)
|
|
|
|
// NewRedisClient 创建 Redis 客户端并验证连接
|
|
func NewRedisClient(cfg config.RedisConfig) (*redis.Client, error) {
|
|
client := redis.NewClient(&redis.Options{
|
|
Addr: fmt.Sprintf("%s:%s", cfg.Host, cfg.Port),
|
|
Password: cfg.Password,
|
|
DB: cfg.DB,
|
|
})
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
if err := client.Ping(ctx).Err(); err != nil {
|
|
return nil, fmt.Errorf("Redis 连接失败: %w", err)
|
|
}
|
|
|
|
return client, nil
|
|
}
|