redis.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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) GetHSet(key string) map[string]string {
  63. return r.GetHSetWithContext(context.Background(), key)
  64. }
  65. func (r *RedisCache) GetHSetWithContext(ctx context.Context, key string) map[string]string {
  66. value, _ := r.redisTemplate.HGetAll(ctx, key).Result()
  67. return value
  68. }
  69. func (r *RedisCache) SetHSet(key string, timeout time.Duration, val ...interface{}) error {
  70. return r.SetHSetWithContext(context.Background(), key, timeout, val...)
  71. }
  72. func (r *RedisCache) SetHSetWithContext(ctx context.Context, key string, timeout time.Duration, val ...interface{}) error {
  73. err := r.redisTemplate.HSet(ctx, key, val...).Err()
  74. if err != nil {
  75. return err
  76. }
  77. return r.redisTemplate.Expire(ctx, key, timeout).Err()
  78. }
  79. // GetString 获取一个值
  80. func (r *RedisCache) GetString(key string) string {
  81. return r.GetStringWithContext(context.Background(), key)
  82. }
  83. // GetStringWithContext 获取一个值
  84. func (r *RedisCache) GetStringWithContext(ctx context.Context, key string) (value string) {
  85. value, _ = r.redisTemplate.Get(ctx, key).Result()
  86. return
  87. }
  88. // SetString 设置一个值
  89. func (r *RedisCache) SetString(key string, val string, expired int) error {
  90. return r.SetStringWithContext(context.Background(), key, val, expired)
  91. }
  92. // SetStringWithContext 设置一个值
  93. func (r *RedisCache) SetStringWithContext(ctx context.Context, key string, val string, expired int) error {
  94. if expired <= 0 {
  95. return r.redisTemplate.Set(ctx, key, val, time.Duration(expired)).Err()
  96. }
  97. return r.redisTemplate.SetEX(ctx, key, val, time.Duration(expired)*time.Second).Err()
  98. }
  99. // IsExist 判断key是否存在
  100. func (r *RedisCache) IsExist(key string) bool {
  101. return r.IsExistWithContext(context.Background(), key)
  102. }
  103. // IsExistWithContext 判断key是否存在
  104. func (r *RedisCache) IsExistWithContext(ctx context.Context, key string) bool {
  105. result, _ := r.redisTemplate.Exists(ctx, key).Result()
  106. return result > 0
  107. }
  108. func (r *RedisCache) SetIfNotExist(key string, val string, expired int) bool {
  109. return r.SetIfNotExistWithContext(context.Background(), key, val, expired)
  110. }
  111. func (r *RedisCache) SetIfNotExistWithContext(ctx context.Context, key string, val string, expired int) bool {
  112. return r.redisTemplate.SetNX(ctx, key, val, time.Duration(expired)*time.Second).Val()
  113. }
  114. // Delete 删除
  115. func (r *RedisCache) Delete(key string) error {
  116. return r.DeleteWithContext(context.Background(), key)
  117. }
  118. // DeleteWithContext 删除
  119. func (r *RedisCache) DeleteWithContext(ctx context.Context, key string) error {
  120. return r.redisTemplate.Del(ctx, key).Err()
  121. }
  122. // Do 执行指令
  123. func (r *RedisCache) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  124. return r.DoWithContext(context.Background(), commandName, args...)
  125. }
  126. // DoWithContext 执行指令
  127. func (r *RedisCache) DoWithContext(ctx context.Context, commandName string, args ...interface{}) (reply interface{}, err error) {
  128. newArgs := []interface{}{commandName}
  129. newArgs = append(newArgs, args...)
  130. return r.redisTemplate.Do(ctx, newArgs...).Result()
  131. }
  132. func (r *RedisCache) RedisClient() redis.UniversalClient {
  133. return r.redisTemplate
  134. }