42 lines
1.4 KiB
Go
42 lines
1.4 KiB
Go
package redismodel
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"git.lzcwy.cn/zhengchiliu/zt-closet-backend/pkg/setting"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// RedisPrefix 是所有 Redis key 的全局命名空间前缀,避免多服务共享 Redis 实例时发生 key 冲突。
|
|
const RedisPrefix = "ztcloset:"
|
|
|
|
// NewRedisClient 根据配置创建 Redis 客户端并验证连接。
|
|
func NewRedisEngine(s *setting.RedisSettingS) (*redis.Client, error) {
|
|
client := redis.NewClient(&redis.Options{
|
|
Addr: fmt.Sprintf("%s:%d", s.Host, s.Port),
|
|
Password: s.Password,
|
|
DB: s.DB,
|
|
PoolSize: s.PoolSize,
|
|
MinIdleConns: s.MinIdleConns,
|
|
MaxIdleConns: s.MaxIdleConns,
|
|
MinRetryBackoff: time.Duration(s.MinRetryBackoff) * time.Millisecond,
|
|
MaxRetryBackoff: time.Duration(s.MaxRetryBackoff) * time.Millisecond,
|
|
MaxRetries: s.MaxRetries,
|
|
// 连接/读写/池超时配置单位为秒(与 config.yaml 注释一致)。
|
|
DialTimeout: time.Duration(s.DialTimeout) * time.Second,
|
|
ReadTimeout: time.Duration(s.ReadTimeout) * time.Second,
|
|
WriteTimeout: time.Duration(s.WriteTimeout) * time.Second,
|
|
PoolTimeout: time.Duration(s.PoolTimeout) * time.Second,
|
|
})
|
|
|
|
if err := client.Ping(context.Background()).Err(); err != nil {
|
|
return nil, fmt.Errorf("redis ping failed: %w", err)
|
|
}
|
|
|
|
slog.Info("redis connected", "addr", fmt.Sprintf("%s:%d", s.Host, s.Port))
|
|
return client, nil
|
|
}
|