cluster_redis.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. // BrpopWithTimeout
  214. // @Description: 从list中读取
  215. // @receiver rc
  216. // @param key
  217. // @param timeout
  218. // @param callback
  219. func (rc *ClusterRedisClient) BrpopWithTimeout(key string, timeout time.Duration, callback func([]byte)) (err error) {
  220. values, err := rc.redisClient.BRPop(context.TODO(), timeout, key).Result()
  221. if err != nil {
  222. return
  223. }
  224. if len(values) < 2 {
  225. err = errors.New("redis brpop timeout")
  226. return
  227. }
  228. callback([]byte(values[1]))
  229. return
  230. }
  231. // LLen
  232. // @Description: 获取list中剩余的数据数
  233. // @author: Roc
  234. // @receiver rc
  235. // @datetime 2025-04-25 10:58:25
  236. // @param key string
  237. // @return int64
  238. // @return error
  239. func (rc *ClusterRedisClient) LLen(key string) (int64, error) {
  240. return rc.redisClient.LLen(context.TODO(), key).Result()
  241. }
  242. // GetRedisTTL
  243. // @Description: 获取key的过期时间
  244. // @receiver rc
  245. // @param key
  246. // @return time.Duration
  247. func (rc *ClusterRedisClient) GetRedisTTL(key string) time.Duration {
  248. value, err := rc.redisClient.TTL(context.TODO(), key).Result()
  249. if err != nil {
  250. return 0
  251. }
  252. return value
  253. }
  254. // Incrby
  255. // @Description: 设置自增值
  256. // @receiver rc
  257. // @param key
  258. // @param num
  259. // @return interface{}
  260. // @return error
  261. func (rc *ClusterRedisClient) Incrby(key string, num int) (interface{}, error) {
  262. return rc.redisClient.IncrBy(context.TODO(), key, int64(num)).Result()
  263. }
  264. // Do
  265. // @Description: cmd执行redis命令
  266. // @receiver rc
  267. // @param commandName
  268. // @param args
  269. // @return reply
  270. // @return err
  271. func (rc *ClusterRedisClient) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  272. newArgs := []interface{}{commandName}
  273. newArgs = append(newArgs, args...)
  274. return rc.redisClient.Do(context.TODO(), newArgs...).Result()
  275. }
  276. // SAdd
  277. // @Description: 写入set元素
  278. // @receiver rc
  279. // @param commandName
  280. // @param args
  281. // @return reply
  282. // @return err
  283. func (rc *ClusterRedisClient) SAdd(key string, args ...interface{}) (err error) {
  284. return rc.redisClient.SAdd(context.TODO(), key, args...).Err()
  285. }
  286. // SAdd
  287. // @Description: 删除set集合中指定的元素
  288. // @receiver rc
  289. // @param commandName
  290. // @param args
  291. // @return reply
  292. // @return err
  293. func (rc *ClusterRedisClient) SRem(key string, args ...interface{}) (err error) {
  294. return rc.redisClient.SRem(context.TODO(), key, args...).Err()
  295. }
  296. // SAdd
  297. // @Description: 判断元素是否在集合中
  298. // @receiver rc
  299. // @param commandName
  300. // @param args
  301. // @return reply
  302. // @return err
  303. func (rc *ClusterRedisClient) SIsMember(key string, args interface{}) (isMember bool, err error) {
  304. isMember, err = rc.redisClient.SIsMember(context.TODO(), key, args).Result()
  305. return
  306. }
  307. func (rc *ClusterRedisClient) ZAdd(key string, members ...*Zset) error {
  308. var redisMembers []*redis.Z
  309. for _, member := range members {
  310. redisMembers = append(redisMembers, &redis.Z{
  311. Member: member.Member,
  312. Score: member.Score,
  313. })
  314. }
  315. return rc.redisClient.ZAdd(context.TODO(), key, redisMembers...).Err()
  316. }
  317. func (rc *ClusterRedisClient) ZRangeWithScores(key string) (result []*Zset, err error) {
  318. redisZList, err := rc.redisClient.ZRangeWithScores(context.TODO(), key, 0, -1).Result()
  319. if err != nil {
  320. return
  321. }
  322. for _, redisZ := range redisZList {
  323. result = append(result, &Zset{
  324. Member: redisZ.Member,
  325. Score: redisZ.Score,
  326. })
  327. }
  328. return
  329. }
  330. func (rc *ClusterRedisClient) Expire(key string, duration time.Duration) error {
  331. return rc.redisClient.Expire(context.Background(), key, duration).Err()
  332. }
  333. func (rc *ClusterRedisClient) Keys(pattern string) (keys []string, err error) {
  334. return rc.redisClient.Keys(context.Background(), pattern).Result()
  335. }
  336. func (rc *ClusterRedisClient) RedisClient() redis.UniversalClient {
  337. return rc.redisClient
  338. }