redis.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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(err)
  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. return err
  27. }
  28. func ParseRedisOption() *redis.Options {
  29. opt, err := redis.ParseURL(os.Getenv("REDIS_CONN_STRING"))
  30. if err != nil {
  31. panic(err)
  32. }
  33. return opt
  34. }
  35. func RedisSet(key string, value string, expiration time.Duration) error {
  36. ctx := context.Background()
  37. return RDB.Set(ctx, key, value, expiration).Err()
  38. }
  39. func RedisGet(key string) (string, error) {
  40. ctx := context.Background()
  41. return RDB.Get(ctx, key).Result()
  42. }
  43. func RedisDel(key string) error {
  44. ctx := context.Background()
  45. return RDB.Del(ctx, key).Err()
  46. }