ai-gateway/common/redis.go

70 lines
1.6 KiB
Go
Raw Normal View History

2023-04-22 12:39:27 +00:00
package common
import (
"context"
"github.com/go-redis/redis/v8"
2024-01-21 14:56:20 +00:00
"one-api/common/logger"
2023-04-22 12:39:27 +00:00
"os"
"time"
)
var RDB *redis.Client
var RedisEnabled = true
// InitRedisClient This function is called after init()
func InitRedisClient() (err error) {
if os.Getenv("REDIS_CONN_STRING") == "" {
RedisEnabled = false
2024-01-21 14:56:20 +00:00
logger.SysLog("REDIS_CONN_STRING not set, Redis is not enabled")
2023-04-22 12:39:27 +00:00
return nil
}
if os.Getenv("SYNC_FREQUENCY") == "" {
2023-06-22 12:12:33 +00:00
RedisEnabled = false
2024-01-21 14:56:20 +00:00
logger.SysLog("SYNC_FREQUENCY not set, Redis is disabled")
2023-06-22 12:12:33 +00:00
return nil
}
2024-01-21 14:56:20 +00:00
logger.SysLog("Redis is enabled")
2023-04-22 12:39:27 +00:00
opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING"))
if err != nil {
2024-01-21 14:56:20 +00:00
logger.FatalLog("failed to parse Redis connection string: " + err.Error())
2023-04-22 12:39:27 +00:00
}
RDB = redis.NewClient(opt)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = RDB.Ping(ctx).Result()
2023-06-22 02:59:01 +00:00
if err != nil {
2024-01-21 14:56:20 +00:00
logger.FatalLog("Redis ping test failed: " + err.Error())
2023-06-22 02:59:01 +00:00
}
2023-04-22 12:39:27 +00:00
return err
}
func ParseRedisOption() *redis.Options {
opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING"))
if err != nil {
2024-01-21 14:56:20 +00:00
logger.FatalLog("failed to parse Redis connection string: " + err.Error())
2023-04-22 12:39:27 +00:00
}
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()
}