package common import ( "context" "github.com/redis/go-redis/v9" "os" "time" ) var RDB *redis.Client // InitRedisClient This function is called after init() func InitRedisClient() (err error) { SysLog("Redis start connection") redisConnStr := os.Getenv("REDIS_CONN_STRING") if redisConnStr == "" { redisConnStr = "redis://@localhost:6379/0?dial_timeout=5s" } opt, err := redis.ParseURL(redisConnStr) //opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING")) if err != nil { FatalLog("failed to parse Redis connection string: " + err.Error()) } RDB = redis.NewClient(opt) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() _, err = RDB.Ping(ctx).Result() if err != nil { FatalLog("Redis ping test failed: " + err.Error()) } return err } func ParseRedisOption() *redis.Options { opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING")) if err != nil { FatalLog("failed to parse Redis connection string: " + err.Error()) } return opt } func RedisSet(key string, value string, expiration time.Duration) error { ctx := context.Background() return RDB.Set(ctx, key, value, expiration).Err() } func RedisGet(key string) (string, error) { ctx := context.Background() return RDB.Get(ctx, key).Result() } func RedisDel(key string) error { ctx := context.Background() return RDB.Del(ctx, key).Err() } func RedisDecrease(key string, value int64) error { ctx := context.Background() return RDB.DecrBy(ctx, key, value).Err() } func RedisIncrByFloat(key string, value float64) (float64, error) { ctx := context.Background() return RDB.IncrByFloat(ctx, key, value).Result() } func RedisIncr(key string) (int64, error) { ctx := context.Background() return RDB.Incr(ctx, key).Result() } func RedisExpire(key string, timeOut time.Duration) (bool, error) { ctx := context.Background() return RDB.Expire(ctx, key, timeOut).Result() }