redis.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. SysLog("Redis is enabled")
  18. opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING"))
  19. if err != nil {
  20. FatalLog("failed to parse Redis connection string: " + err.Error())
  21. }
  22. RDB = redis.NewClient(opt)
  23. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  24. defer cancel()
  25. _, err = RDB.Ping(ctx).Result()
  26. if err != nil {
  27. FatalLog("Redis ping test failed: " + err.Error())
  28. }
  29. return err
  30. }
  31. func ParseRedisOption() *redis.Options {
  32. opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING"))
  33. if err != nil {
  34. FatalLog("failed to parse Redis connection string: " + err.Error())
  35. }
  36. return opt
  37. }
  38. func RedisSet(key string, value string, expiration time.Duration) error {
  39. ctx := context.Background()
  40. return RDB.Set(ctx, key, value, expiration).Err()
  41. }
  42. func RedisGet(key string) (string, error) {
  43. ctx := context.Background()
  44. return RDB.Get(ctx, key).Result()
  45. }
  46. func RedisDel(key string) error {
  47. ctx := context.Background()
  48. return RDB.Del(ctx, key).Err()
  49. }