cluster_redis.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package redis
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/go-redis/redis/v8"
  8. "strings"
  9. "time"
  10. )
  11. // ClusterRedisClient
  12. // @Description:
  13. type ClusterRedisClient struct {
  14. redisClient *redis.ClusterClient
  15. }
  16. var DefaultKey = "zcmRedis"
  17. func InitClusterRedis(config string) (clusterRedisClient *ClusterRedisClient, err error) {
  18. var cf map[string]string
  19. err = json.Unmarshal([]byte(config), &cf)
  20. if err != nil {
  21. return
  22. }
  23. //if _, ok := cf["key"]; !ok {
  24. // cf["key"] = DefaultKey
  25. //}
  26. // 集群地址
  27. connList := make([]string, 0)
  28. if _, ok := cf["conn"]; !ok {
  29. err = errors.New("config has no conn key")
  30. return
  31. } else {
  32. connList = strings.Split(cf["conn"], ",")
  33. if len(connList) <= 1 {
  34. err = errors.New("conn address less than or equal to 1")
  35. return
  36. }
  37. }
  38. // 密码
  39. if _, ok := cf["password"]; !ok {
  40. cf["password"] = ""
  41. }
  42. // 创建 Redis 客户端配置对象
  43. clusterOptions := &redis.ClusterOptions{
  44. Addrs: connList, // 设置 Redis 节点的 IP 地址和端口号
  45. Password: cf["password"],
  46. }
  47. // 创建 Redis 集群客户端
  48. client := redis.NewClusterClient(clusterOptions)
  49. // 测试连接并获取信息
  50. _, err = client.Ping(context.TODO()).Result()
  51. if err != nil {
  52. err = errors.New("redis 链接失败:" + err.Error())
  53. return
  54. }
  55. clusterRedisClient = &ClusterRedisClient{redisClient: client}
  56. return
  57. }
  58. // Get cache from redis.
  59. func (rc *ClusterRedisClient) Get(key string) interface{} {
  60. data, err := rc.redisClient.Get(context.TODO(), key).Bytes()
  61. if err != nil {
  62. return nil
  63. }
  64. return data
  65. }
  66. func (rc *ClusterRedisClient) RedisBytes(key string) (data []byte, err error) {
  67. data, err = rc.redisClient.Get(context.TODO(), key).Bytes()
  68. return
  69. }
  70. func (rc *ClusterRedisClient) RedisString(key string) (data string, err error) {
  71. data, err = rc.redisClient.Get(context.TODO(), key).Result()
  72. return
  73. }
  74. func (rc *ClusterRedisClient) RedisInt(key string) (data int, err error) {
  75. data, err = rc.redisClient.Get(context.TODO(), key).Int()
  76. return
  77. }
  78. // Put put cache to redis.
  79. func (rc *ClusterRedisClient) Put(key string, val interface{}, timeout time.Duration) error {
  80. var err error
  81. err = rc.redisClient.SetEX(context.TODO(), key, val, timeout).Err()
  82. if err != nil {
  83. return err
  84. }
  85. err = rc.redisClient.HSet(context.TODO(), DefaultKey, key, true).Err()
  86. return err
  87. }
  88. func (rc *ClusterRedisClient) SetNX(key string, val interface{}, timeout time.Duration) bool {
  89. result, err := rc.redisClient.SetEX(context.TODO(), key, val, timeout).Result()
  90. if err != nil || result != "OK" {
  91. return false
  92. }
  93. return true
  94. }
  95. // Delete delete cache in redis.
  96. func (rc *ClusterRedisClient) Delete(key string) error {
  97. var err error
  98. err = rc.redisClient.Del(context.TODO(), key).Err()
  99. if err != nil {
  100. return err
  101. }
  102. err = rc.redisClient.HDel(context.TODO(), DefaultKey, key).Err()
  103. return err
  104. }
  105. // IsExist check cache's existence in redis.
  106. func (rc *ClusterRedisClient) IsExist(key string) bool {
  107. result, err := rc.redisClient.Exists(context.TODO(), key).Result()
  108. if err != nil {
  109. return false
  110. }
  111. if result == 0 {
  112. err = rc.redisClient.HDel(context.TODO(), DefaultKey, key).Err()
  113. if err != nil {
  114. return false
  115. }
  116. }
  117. return true
  118. }
  119. // Put put cache to redis.
  120. func (rc *ClusterRedisClient) LPush(key string, val interface{}) error {
  121. data, _ := json.Marshal(val)
  122. err := rc.redisClient.LPush(context.TODO(), key, data).Err()
  123. return err
  124. }
  125. func (rc *ClusterRedisClient) Brpop(key string, callback func([]byte)) {
  126. values, err := rc.redisClient.BRPop(context.TODO(), 1*time.Second, key).Result()
  127. if err != nil {
  128. return
  129. }
  130. if len(values) < 2 {
  131. fmt.Println("assert is wrong")
  132. return
  133. }
  134. callback([]byte(values[1]))
  135. }
  136. func (rc *ClusterRedisClient) GetRedisTTL(key string) time.Duration {
  137. value, err := rc.redisClient.TTL(context.TODO(), key).Result()
  138. if err != nil {
  139. return 0
  140. }
  141. return value
  142. }
  143. // Decr decrease counter in redis.
  144. func (rc *ClusterRedisClient) Incrby(key string, num int) (interface{}, error) {
  145. return rc.redisClient.IncrBy(context.TODO(), key, int64(num)).Result()
  146. }
  147. // actually do the redis cmds
  148. func (rc *ClusterRedisClient) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  149. newArgs := make([]interface{}, 0)
  150. newArgs = append(newArgs, commandName, args)
  151. return rc.redisClient.Do(context.TODO(), commandName, newArgs).Result()
  152. }