redis.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package common
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "github.com/labring/aiproxy/core/common/config"
  8. "github.com/redis/go-redis/v9"
  9. log "github.com/sirupsen/logrus"
  10. )
  11. var (
  12. RDB *redis.Client
  13. RedisEnabled = false
  14. )
  15. const defaultRedisKeyPrefix = "aiproxy"
  16. func RedisKeyPrefix() string {
  17. if config.RedisKeyPrefix == "" {
  18. return defaultRedisKeyPrefix
  19. }
  20. return config.RedisKeyPrefix
  21. }
  22. func RedisKeyf(format string, args ...any) string {
  23. if len(args) == 0 {
  24. return RedisKeyPrefix() + ":" + format
  25. }
  26. return RedisKeyPrefix() + ":" + fmt.Sprintf(format, args...)
  27. }
  28. func RedisKey(keys ...string) string {
  29. if len(keys) == 0 {
  30. panic("redis keys is empty")
  31. }
  32. if len(keys) == 1 {
  33. return RedisKeyPrefix() + ":" + keys[0]
  34. }
  35. return RedisKeyPrefix() + ":" + strings.Join(keys, ":")
  36. }
  37. // InitRedisClient This function is called after init()
  38. func InitRedisClient() (err error) {
  39. redisConn := config.Redis
  40. if redisConn == "" {
  41. log.Info("REDIS not set, redis is not enabled")
  42. return nil
  43. }
  44. RedisEnabled = true
  45. log.Info("redis is enabled")
  46. opt, err := redis.ParseURL(redisConn)
  47. if err != nil {
  48. log.Fatal("failed to parse redis connection string: " + err.Error())
  49. }
  50. RDB = redis.NewClient(opt)
  51. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  52. defer cancel()
  53. _, err = RDB.Ping(ctx).Result()
  54. if err != nil {
  55. log.Errorf("failed to ping redis: %s", err.Error())
  56. }
  57. return nil
  58. }