redis.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package common
  2. import (
  3. "context"
  4. "github.com/go-redis/redis/v8"
  5. "os"
  6. "time"
  7. )
  8. var RDB *redis.Client
  9. var RedisEnabled = true
  10. // InitRedisClient This function is called after init()
  11. func InitRedisClient() (err error) {
  12. if os.Getenv("REDIS_CONN_STRING") == "" {
  13. RedisEnabled = false
  14. SysLog("REDIS_CONN_STRING not set, Redis is not enabled")
  15. return nil
  16. }
  17. if os.Getenv("SYNC_FREQUENCY") == "" {
  18. RedisEnabled = false
  19. SysLog("SYNC_FREQUENCY not set, Redis is disabled")
  20. return nil
  21. }
  22. SysLog("Redis is enabled")
  23. opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING"))
  24. if err != nil {
  25. FatalLog("failed to parse Redis connection string: " + err.Error())
  26. }
  27. RDB = redis.NewClient(opt)
  28. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  29. defer cancel()
  30. _, err = RDB.Ping(ctx).Result()
  31. if err != nil {
  32. FatalLog("Redis ping test failed: " + err.Error())
  33. }
  34. return err
  35. }
  36. func ParseRedisOption() *redis.Options {
  37. opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING"))
  38. if err != nil {
  39. FatalLog("failed to parse Redis connection string: " + err.Error())
  40. }
  41. return opt
  42. }
  43. func RedisSet(key string, value string, expiration time.Duration) error {
  44. ctx := context.Background()
  45. return RDB.Set(ctx, key, value, expiration).Err()
  46. }
  47. func RedisGet(key string) (string, error) {
  48. ctx := context.Background()
  49. return RDB.Get(ctx, key).Result()
  50. }
  51. func RedisDel(key string) error {
  52. ctx := context.Background()
  53. return RDB.Del(ctx, key).Err()
  54. }