cluster_redis.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package redis
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/go-redis/redis/v8"
  10. )
  11. // ClusterRedisClient
  12. // @Description: 集群的redis客户端
  13. type ClusterRedisClient struct {
  14. redisClient *redis.ClusterClient
  15. }
  16. type Zset struct {
  17. Score float64
  18. Member interface{}
  19. }
  20. var DefaultKey = "zcmRedis"
  21. // InitClusterRedis
  22. // @Description: 初始化集群redis客户端
  23. // @param config
  24. // @return clusterRedisClient
  25. // @return err
  26. func InitClusterRedis(config string) (clusterRedisClient *ClusterRedisClient, err error) {
  27. var cf map[string]string
  28. err = json.Unmarshal([]byte(config), &cf)
  29. if err != nil {
  30. return
  31. }
  32. //if _, ok := cf["key"]; !ok {
  33. // cf["key"] = DefaultKey
  34. //}
  35. // 集群地址
  36. connList := make([]string, 0)
  37. if _, ok := cf["conn"]; !ok {
  38. err = errors.New("config has no conn key")
  39. return
  40. } else {
  41. connList = strings.Split(cf["conn"], ",")
  42. if len(connList) <= 1 {
  43. err = errors.New("conn address less than or equal to 1")
  44. return
  45. }
  46. }
  47. // 密码
  48. if _, ok := cf["password"]; !ok {
  49. cf["password"] = ""
  50. }
  51. // 创建 Redis 客户端配置对象
  52. clusterOptions := &redis.ClusterOptions{
  53. Addrs: connList, // 设置 Redis 节点的 IP 地址和端口号
  54. Password: cf["password"],
  55. }
  56. // 创建 Redis 集群客户端
  57. client := redis.NewClusterClient(clusterOptions)
  58. // 测试连接并获取信息
  59. _, err = client.Ping(context.TODO()).Result()
  60. if err != nil {
  61. err = errors.New("redis 链接失败:" + err.Error())
  62. return
  63. }
  64. clusterRedisClient = &ClusterRedisClient{redisClient: client}
  65. return
  66. }
  67. // Get
  68. // @Description: 根据key获取数据(其实是返回的字节编码)
  69. // @receiver rc
  70. // @param key
  71. // @return interface{}
  72. func (rc *ClusterRedisClient) Get(key string) interface{} {
  73. data, err := rc.redisClient.Get(context.TODO(), key).Bytes()
  74. if err != nil {
  75. return nil
  76. }
  77. return data
  78. }
  79. // GetStr
  80. // @Description: 根据key获取字符串数据
  81. // @receiver rc
  82. // @param key
  83. // @return string
  84. func (rc *ClusterRedisClient) GetStr(key string) string {
  85. return rc.redisClient.Get(context.TODO(), key).Val()
  86. }
  87. // GetUInt64
  88. // @Description: 根据key获取uint64数据
  89. // @receiver rc
  90. // @param key
  91. // @return int
  92. // @return error
  93. func (rc *ClusterRedisClient) GetUInt64(key string) (uint64, error) {
  94. return rc.redisClient.Get(context.TODO(), key).Uint64()
  95. }
  96. // RedisBytes
  97. // @Description: 根据key获取字节编码数据
  98. // @receiver rc
  99. // @param key
  100. // @return data
  101. // @return err
  102. func (rc *ClusterRedisClient) RedisBytes(key string) (data []byte, err error) {
  103. data, err = rc.redisClient.Get(context.TODO(), key).Bytes()
  104. return
  105. }
  106. // RedisString
  107. // @Description: 根据key获取字符串数据
  108. // @receiver rc
  109. // @param key
  110. // @return data
  111. // @return err
  112. func (rc *ClusterRedisClient) RedisString(key string) (data string, err error) {
  113. data, err = rc.redisClient.Get(context.TODO(), key).Result()
  114. return
  115. }
  116. // RedisInt
  117. // @Description: 根据key获取int数据
  118. // @receiver rc
  119. // @param key
  120. // @return data
  121. // @return err
  122. func (rc *ClusterRedisClient) RedisInt(key string) (data int, err error) {
  123. data, err = rc.redisClient.Get(context.TODO(), key).Int()
  124. return
  125. }
  126. // Put
  127. // @Description: put一个数据到redis
  128. // @receiver rc
  129. // @param key
  130. // @param val
  131. // @param timeout
  132. // @return error
  133. func (rc *ClusterRedisClient) Put(key string, val interface{}, timeout time.Duration) error {
  134. var err error
  135. err = rc.redisClient.SetEX(context.TODO(), key, val, timeout).Err()
  136. if err != nil {
  137. return err
  138. }
  139. err = rc.redisClient.HSet(context.TODO(), DefaultKey, key, true).Err()
  140. return err
  141. }
  142. // SetNX
  143. // @Description: 设置一个会过期时间的值
  144. // @receiver rc
  145. // @param key
  146. // @param val
  147. // @param timeout
  148. // @return bool
  149. func (rc *ClusterRedisClient) SetNX(key string, val interface{}, timeout time.Duration) bool {
  150. result, err := rc.redisClient.SetNX(context.TODO(), key, val, timeout).Result()
  151. if err != nil {
  152. return false
  153. }
  154. return result
  155. }
  156. // Delete
  157. // @Description: 删除redis中的键值对
  158. // @receiver rc
  159. // @param key
  160. // @return error
  161. func (rc *ClusterRedisClient) Delete(key string) error {
  162. var err error
  163. err = rc.redisClient.Del(context.TODO(), key).Err()
  164. if err != nil {
  165. return err
  166. }
  167. err = rc.redisClient.HDel(context.TODO(), DefaultKey, key).Err()
  168. return err
  169. }
  170. // IsExist
  171. // @Description: 根据key判断是否写入缓存中
  172. // @receiver rc
  173. // @param key
  174. // @return bool
  175. func (rc *ClusterRedisClient) IsExist(key string) bool {
  176. result, err := rc.redisClient.Exists(context.TODO(), key).Result()
  177. if err != nil {
  178. return false
  179. }
  180. if result == 0 {
  181. _ = rc.redisClient.HDel(context.TODO(), DefaultKey, key).Err()
  182. return false
  183. }
  184. return true
  185. }
  186. // LPush
  187. // @Description: 写入list
  188. // @receiver rc
  189. // @param key
  190. // @param val
  191. // @return error
  192. func (rc *ClusterRedisClient) LPush(key string, val interface{}) error {
  193. data, _ := json.Marshal(val)
  194. err := rc.redisClient.LPush(context.TODO(), key, data).Err()
  195. return err
  196. }
  197. // Brpop
  198. // @Description: 从list中读取
  199. // @receiver rc
  200. // @param key
  201. // @param callback
  202. func (rc *ClusterRedisClient) Brpop(key string, callback func([]byte)) {
  203. values, err := rc.redisClient.BRPop(context.TODO(), 1*time.Second, key).Result()
  204. if err != nil {
  205. return
  206. }
  207. if len(values) < 2 {
  208. fmt.Println("assert is wrong")
  209. return
  210. }
  211. callback([]byte(values[1]))
  212. }
  213. // GetRedisTTL
  214. // @Description: 获取key的过期时间
  215. // @receiver rc
  216. // @param key
  217. // @return time.Duration
  218. func (rc *ClusterRedisClient) GetRedisTTL(key string) time.Duration {
  219. value, err := rc.redisClient.TTL(context.TODO(), key).Result()
  220. if err != nil {
  221. return 0
  222. }
  223. return value
  224. }
  225. // Incrby
  226. // @Description: 设置自增值
  227. // @receiver rc
  228. // @param key
  229. // @param num
  230. // @return interface{}
  231. // @return error
  232. func (rc *ClusterRedisClient) Incrby(key string, num int) (interface{}, error) {
  233. return rc.redisClient.IncrBy(context.TODO(), key, int64(num)).Result()
  234. }
  235. // Do
  236. // @Description: cmd执行redis命令
  237. // @receiver rc
  238. // @param commandName
  239. // @param args
  240. // @return reply
  241. // @return err
  242. func (rc *ClusterRedisClient) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  243. newArgs := []interface{}{commandName}
  244. newArgs = append(newArgs, args...)
  245. return rc.redisClient.Do(context.TODO(), newArgs...).Result()
  246. }
  247. // SAdd
  248. // @Description: 写入set元素
  249. // @receiver rc
  250. // @param commandName
  251. // @param args
  252. // @return reply
  253. // @return err
  254. func (rc *ClusterRedisClient) SAdd(key string, args ...interface{}) (err error) {
  255. return rc.redisClient.SAdd(context.TODO(), key, args...).Err()
  256. }
  257. // SAdd
  258. // @Description: 删除set集合中指定的元素
  259. // @receiver rc
  260. // @param commandName
  261. // @param args
  262. // @return reply
  263. // @return err
  264. func (rc *ClusterRedisClient) SRem(key string, args ...interface{}) (err error) {
  265. return rc.redisClient.SRem(context.TODO(), key, args...).Err()
  266. }
  267. // SAdd
  268. // @Description: 判断元素是否在集合中
  269. // @receiver rc
  270. // @param commandName
  271. // @param args
  272. // @return reply
  273. // @return err
  274. func (rc *ClusterRedisClient) SIsMember(key string, args interface{}) (isMember bool, err error) {
  275. isMember, err = rc.redisClient.SIsMember(context.TODO(), key, args).Result()
  276. return
  277. }
  278. func (rc *ClusterRedisClient) ZAdd(key string, members ...*Zset) error {
  279. var redisMembers []*redis.Z
  280. for _, member := range members {
  281. redisMembers = append(redisMembers, &redis.Z{
  282. Member: member.Member,
  283. Score: member.Score,
  284. })
  285. }
  286. return rc.redisClient.ZAdd(context.TODO(), key, redisMembers...).Err()
  287. }
  288. func (rc *ClusterRedisClient) ZRangeWithScores(key string) (result []*Zset, err error) {
  289. redisZList, err := rc.redisClient.ZRangeWithScores(context.TODO(), key, 0, -1).Result()
  290. if err != nil {
  291. return
  292. }
  293. for _, redisZ := range redisZList {
  294. result = append(result, &Zset{
  295. Member: redisZ.Member,
  296. Score: redisZ.Score,
  297. })
  298. }
  299. return
  300. }
  301. func (rc *ClusterRedisClient) Expire(key string, duration time.Duration) error {
  302. return rc.redisClient.Expire(context.Background(), key, duration).Err()
  303. }
  304. func (rc *ClusterRedisClient) Keys(pattern string) (keys []string, err error) {
  305. return rc.redisClient.Keys(context.Background(), pattern).Result()
  306. }
  307. func (rc *ClusterRedisClient) RedisClient() redis.UniversalClient {
  308. return rc.redisClient
  309. }