package redis_tools import ( "apiServer_service/utils/logger" "context" "os" "sync" "time" "github.com/go-redis/redis/v8" ) var ( client *redis.Client once sync.Once ) func ConnectRedis() *redis.Client { once.Do(func() { addr := os.Getenv("REDIS_HOST") if addr == "" { addr = "127.0.0.1:6379" } password := os.Getenv("REDIS_PASSWORD") client = redis.NewClient(&redis.Options{ Addr: addr, Password: password, DB: 0, PoolSize: 20, MinIdleConns: 5, DialTimeout: 5 * time.Second, ReadTimeout: 3 * time.Second, WriteTimeout: 3 * time.Second, }) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := client.Ping(ctx).Err(); err != nil { logger.Warn("Redis", "连接失败: ", err) return } logger.Info("Redis", "连接成功") }) return client } func GetClient() *redis.Client { return ConnectRedis() } func Close() error { if client != nil { return client.Close() } return nil } // ---- List 操作 ---- func AddToList(key string, value interface{}) error { return GetClient().LPush(context.Background(), key, value).Err() } func GetListRange(key string, start, stop int64) ([]string, error) { return GetClient().LRange(context.Background(), key, start, stop).Result() } func GetAllFromList(key string) ([]string, error) { return GetListRange(key, 0, -1) } func RemoveFromList(key string, value interface{}) error { return GetClient().LRem(context.Background(), key, 0, value).Err() } // ---- KV 缓存操作 ---- func SetCache(key string, value interface{}, expiration time.Duration) error { return GetClient().Set(context.Background(), key, value, expiration).Err() } func GetCache(key string) (string, error) { return GetClient().Get(context.Background(), key).Result() } func Exists(key string) bool { n, err := GetClient().Exists(context.Background(), key).Result() return err == nil && n > 0 } func Del(keys ...string) error { return GetClient().Del(context.Background(), keys...).Err() }