redis.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. }
  55. func RedisDecrease(key string, value int64) error {
  56. ctx := context.Background()
  57. return RDB.DecrBy(ctx, key, value).Err()
  58. }