package cache import ( "context" "eta_mini_ht_api/common/component/config" logger "eta_mini_ht_api/common/component/log" "github.com/go-redis/redis/v8" "log" "strings" "sync" "time" ) var ( redisCache *RedisCache once sync.Once ) func GetInstance() *RedisCache { once.Do(func() { redisConf, ok := config.GetConfig("redis").(*config.RedisConfig) // 检查是否成功获取到RedisConfig实例 if !ok { logger.Info("加载redis配置失败") return } opts, ok := redisConf.GetConfig().(config.RedisOpts) // 检查Host是否已设置,然后初始化或执行相应操作 if ok && opts.Host != "" { logger.Info("初始化redis") // 这里可以添加初始化Redis的逻辑 redisCache = newRedis(opts) } else { logger.Info("Redis configuration is incomplete: Host is missing") return } }) return redisCache } func newRedis(opts config.RedisOpts) *RedisCache { if &opts == nil || opts.Host == "" { log.Fatalf("redis 连接失败") } redisTemplate := redis.NewUniversalClient(&redis.UniversalOptions{ Addrs: strings.Split(opts.Host, ";"), DB: opts.Database, Password: opts.Password, IdleTimeout: time.Second * time.Duration(opts.IdleTimeout), MinIdleConns: opts.MaxIdle, }) return &RedisCache{redisTemplate: redisTemplate} } // RedisCache // @Description: redis缓存 type RedisCache struct { redisTemplate redis.UniversalClient } // GetString 获取一个值 func (r *RedisCache) GetString(key string) string { return r.GetStringWithContext(context.Background(), key) } // GetStringWithContext 获取一个值 func (r *RedisCache) GetStringWithContext(ctx context.Context, key string) (value string) { value, _ = r.redisTemplate.Get(ctx, key).Result() return } // SetString 设置一个值 func (r *RedisCache) SetString(key string, val string, timeout time.Duration) error { return r.redisTemplate.SetEX(context.Background(), key, val, timeout).Err() } // SetStringWithContext 设置一个值 func (r *RedisCache) SetStringWithContext(ctx context.Context, key string, val string, timeout time.Duration) error { return r.redisTemplate.SetEX(ctx, key, val, timeout).Err() } // IsExist 判断key是否存在 func (r *RedisCache) IsExist(key string) bool { return r.IsExistWithContext(context.Background(), key) } // IsExistWithContext 判断key是否存在 func (r *RedisCache) IsExistWithContext(ctx context.Context, key string) bool { result, _ := r.redisTemplate.Exists(ctx, key).Result() return result > 0 } // Delete 删除 func (r *RedisCache) Delete(key string) error { return r.DeleteWithContext(context.Background(), key) } // DeleteWithContext 删除 func (r *RedisCache) DeleteWithContext(ctx context.Context, key string) error { return r.redisTemplate.Del(ctx, key).Err() } // Do 执行指令 func (r *RedisCache) Do(commandName string, args ...interface{}) (reply interface{}, err error) { return r.DoWithContext(context.Background(), commandName, args...) } // DoWithContext 执行指令 func (r *RedisCache) DoWithContext(ctx context.Context, commandName string, args ...interface{}) (reply interface{}, err error) { newArgs := []interface{}{commandName} newArgs = append(newArgs, args...) return r.redisTemplate.Do(ctx, newArgs...).Result() }