You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.8 KiB

3 years ago
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")
opt, err := redis.ParseURL("redis://@localhost:6379/0?dial_timeout=5s")
//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()
}