redis.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package cache
  2. import (
  3. "context"
  4. "eta/eta_mini_ht_api/common/component/config"
  5. logger "eta/eta_mini_ht_api/common/component/log"
  6. "eta/eta_mini_ht_api/common/contants"
  7. "github.com/go-redis/redis/v8"
  8. "log"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var (
  14. redisCache *RedisCache
  15. redisOnce sync.Once
  16. )
  17. func init() {
  18. if GetInstance() == nil {
  19. panic("初始化redis失败")
  20. }
  21. logger.Info("redis初始化成功")
  22. }
  23. func GetInstance() *RedisCache {
  24. redisOnce.Do(func() {
  25. // 检查是否成功获取到RedisConfig实例,没有配置则不进行redis初始化
  26. if redisConf, ok := config.GetConfig(contants.REDIS).(*config.RedisConfig); ok {
  27. if redisConf.GetHost() != "" {
  28. logger.Info("初始化redis")
  29. // 这里可以添加初始化Redis的逻辑
  30. redisCache = newRedis(redisConf)
  31. _, err := redisCache.Do("Ping")
  32. if err != nil {
  33. log.Fatalf("redis 链接失败:%v", err)
  34. }
  35. logger.Info("redis地址:%v", redisConf.GetHost())
  36. } else {
  37. logger.Info("Redis configuration is incomplete: Host is missing")
  38. return
  39. }
  40. }
  41. })
  42. return redisCache
  43. }
  44. func newRedis(config *config.RedisConfig) *RedisCache {
  45. if &config == nil || config.GetHost() == "" {
  46. log.Fatalf("redis 连接失败")
  47. }
  48. redisTemplate := redis.NewUniversalClient(&redis.UniversalOptions{
  49. Addrs: strings.Split(config.GetHost(), ","),
  50. DB: config.GetDatabase(),
  51. Password: config.GetPassword(),
  52. IdleTimeout: time.Second * time.Duration(config.GetIdleTimeout()),
  53. MinIdleConns: config.GetMaxIdle(),
  54. })
  55. return &RedisCache{redisTemplate: redisTemplate}
  56. }
  57. // RedisCache
  58. // @Description: redis缓存
  59. type RedisCache struct {
  60. redisTemplate redis.UniversalClient
  61. }
  62. func (r *RedisCache) Keys(pattern string) (keys []string, err error) {
  63. keys, err = r.redisTemplate.Keys(context.Background(), pattern).Result()
  64. return
  65. }
  66. func (r *RedisCache) GetHSet(key string) map[string]string {
  67. return r.GetHSetWithContext(context.Background(), key)
  68. }
  69. func (r *RedisCache) GetHSetWithContext(ctx context.Context, key string) map[string]string {
  70. value, _ := r.redisTemplate.HGetAll(ctx, key).Result()
  71. return value
  72. }
  73. func (r *RedisCache) SetHSet(key string, timeout time.Duration, val ...interface{}) error {
  74. return r.SetHSetWithContext(context.Background(), key, timeout, val...)
  75. }
  76. func (r *RedisCache) SetHSetWithContext(ctx context.Context, key string, timeout time.Duration, val ...interface{}) error {
  77. err := r.redisTemplate.HSet(ctx, key, val...).Err()
  78. if err != nil {
  79. return err
  80. }
  81. return r.redisTemplate.Expire(ctx, key, timeout).Err()
  82. }
  83. // UpdateHSetNoExpire 仅更新 HSet 的值,不更改其过期时间
  84. func (r *RedisCache) UpdateHSetNoExpire(key string, val ...interface{}) error {
  85. return r.UpdateHSetNoExpireWithContext(context.Background(), key, val...)
  86. }
  87. // UpdateHSetNoExpireWithContext 仅更新 HSet 的值,不更改其过期时间(支持上下文)
  88. func (r *RedisCache) UpdateHSetNoExpireWithContext(ctx context.Context, key string, val ...interface{}) error {
  89. return r.redisTemplate.HSet(ctx, key, val...).Err()
  90. }
  91. // GetString 获取一个值
  92. func (r *RedisCache) GetString(key string) string {
  93. return r.GetStringWithContext(context.Background(), key)
  94. }
  95. // GetStringWithContext 获取一个值
  96. func (r *RedisCache) GetStringWithContext(ctx context.Context, key string) (value string) {
  97. value, _ = r.redisTemplate.Get(ctx, key).Result()
  98. return
  99. }
  100. // SetString 设置一个值
  101. func (r *RedisCache) SetString(key string, val string, expired int) error {
  102. return r.SetStringWithContext(context.Background(), key, val, expired)
  103. }
  104. // SetStringWithContext 设置一个值
  105. func (r *RedisCache) SetStringWithContext(ctx context.Context, key string, val string, expired int) error {
  106. if expired <= 0 {
  107. return r.redisTemplate.Set(ctx, key, val, time.Duration(expired)).Err()
  108. }
  109. return r.redisTemplate.SetEX(ctx, key, val, time.Duration(expired)*time.Second).Err()
  110. }
  111. // IsExist 判断key是否存在
  112. func (r *RedisCache) IsExist(key string) bool {
  113. return r.IsExistWithContext(context.Background(), key)
  114. }
  115. // IsExistWithContext 判断key是否存在
  116. func (r *RedisCache) IsExistWithContext(ctx context.Context, key string) bool {
  117. result, _ := r.redisTemplate.Exists(ctx, key).Result()
  118. return result > 0
  119. }
  120. func (r *RedisCache) SetIfNotExist(key string, val string, expired int) bool {
  121. return r.SetIfNotExistWithContext(context.Background(), key, val, expired)
  122. }
  123. func (r *RedisCache) SetIfNotExistWithContext(ctx context.Context, key string, val string, expired int) bool {
  124. return r.redisTemplate.SetNX(ctx, key, val, time.Duration(expired)*time.Second).Val()
  125. }
  126. // Delete 删除
  127. func (r *RedisCache) Delete(key string) error {
  128. return r.DeleteWithContext(context.Background(), key)
  129. }
  130. // DeleteWithContext 删除
  131. func (r *RedisCache) DeleteWithContext(ctx context.Context, key string) error {
  132. return r.redisTemplate.Del(ctx, key).Err()
  133. }
  134. // Do 执行指令
  135. func (r *RedisCache) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  136. return r.DoWithContext(context.Background(), commandName, args...)
  137. }
  138. // DoWithContext 执行指令
  139. func (r *RedisCache) DoWithContext(ctx context.Context, commandName string, args ...interface{}) (reply interface{}, err error) {
  140. newArgs := []interface{}{commandName}
  141. newArgs = append(newArgs, args...)
  142. return r.redisTemplate.Do(ctx, newArgs...).Result()
  143. }
  144. func (r *RedisCache) RedisClient() redis.UniversalClient {
  145. return r.redisTemplate
  146. }