redis.go 1.1 KB

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