goredis.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. package redis
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "hash/crc32"
  7. "log"
  8. "math"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/go-redis/redis/v8"
  14. )
  15. //goredis 工具类对象
  16. type GoRedis struct {
  17. //Password string
  18. Code string
  19. DB int //默认库
  20. DBS []int //数据库列表
  21. Nodes []int //节点列表
  22. HashDb int //是否是多个数据库 0单库 1单节点多库 2多节点单库 3多节点多库
  23. Ctx context.Context
  24. CMap map[int]map[int]*redis.Client
  25. BakDb bool //是否有备用节点
  26. Bak *GoRedis //备用节点连接
  27. }
  28. //code并未实现,目前不支持多个code使用
  29. //初始化单个"[other=]127.0.0.1:2203[|#]127.0.0.1:2204[/0]=0-1=1-10=300" [代码]、地址[|备用地址[/代表默认库][#多节点地址,默认库都为0]、库、最大池、空闲时间默认300秒
  30. /*
  31. 示例
  32. 127.0.0.1:2203
  33. 127.0.0.1:2203=2=15 默认库为2,最大连接为15,最小连接是0.2*15为3
  34. other=127.0.0.1:2203 带code配置
  35. other=127.0.0.1:2203=0=10
  36. other=127.0.0.1:2203=0=10=300 空闲时间300秒
  37. other=127.0.0.1:2203=0-8=10=300 带code配置,使用多个库即0 1 2 3 4 5 6 7 8,最大连接为10,最小连接是0.2*10为2,空闲时间300秒
  38. other=127.0.0.1:2203=0-8=1-10=300 带code配置,使用多个库即0 1 2 3 4 5 6 7 8,最大连接为10,最小连接1,空闲时间300秒
  39. other=127.0.0.1:2203|127.0.0.1:2204=0-8=10=300 带code配置,使用备用节点(仅供取数据时使用),使用多个库即0 1 2 3 4 5 6 7 8,最大连接为10,最小连接1,空闲时间300秒
  40. other=127.0.0.1:2203|127.0.0.1:2204/0=0-8=10=300 带code配置,使用备用节点(仅供取数据时使用,备用节点默认库为0),使用多个库即0 1 2 3 4 5 6 7 8,最大连接为10,最小连接1,空闲时间300秒
  41. other=127.0.0.1:2203#127.0.0.1:2204#127.0.0.1:2205#127.0.0.1:2206=0=10=300 带code配置,使用多节点模式(多节点所有默认库为0),最大连接为10,最小连接2,空闲时间300秒
  42. 注意:
  43. 1、当使用多节点时,用正则获取keys时,再用Get取模获取数据时,一定要保障放入和取出是同一个hashcode,否则数据永远取不到
  44. */
  45. //解析配置并初始化,opt为string或map
  46. func (r *GoRedis) Init(opt interface{}) {
  47. check := false
  48. //代码 地址 []库范围 []池配置 空闲时间
  49. code, addr, dbs, pool, idle := "", "", []int{0}, []int{2, 30}, 300
  50. if so, ok := opt.(string); ok {
  51. arr := strings.Split(so, "=")
  52. regAddr := regexp.MustCompile("[0-9.a-zA-Z/]+:[0-9]+.*")
  53. if len(arr) == 1 { //只是一个串
  54. if regAddr.MatchString(arr[0]) {
  55. check = true
  56. addr = arr[0]
  57. }
  58. } else if len(arr) > 1 {
  59. index := 0
  60. if regAddr.MatchString(arr[0]) { //第1个是地址
  61. index = 1
  62. addr = arr[0]
  63. check = true
  64. } else if regAddr.MatchString(arr[1]) { //第二个是地址
  65. check = true
  66. addr = arr[1]
  67. code = arr[0]
  68. }
  69. //解析库配置
  70. if len(arr) > 2-index { //dbs配置
  71. dbs1 := strings.Split(arr[2-index], "-") //库范围的配置
  72. if len(dbs1) == 1 || len(dbs1) == 2 {
  73. check = true
  74. dbs[0], _ = strconv.Atoi(dbs1[0])
  75. if len(dbs1) == 2 {
  76. tmp, _ := strconv.Atoi(dbs1[1])
  77. dbs = append(dbs, tmp)
  78. }
  79. } else {
  80. check = false
  81. }
  82. //解析连接池配置
  83. if len(arr) > 3-index {
  84. pool1 := strings.Split(arr[3-index], "-")
  85. if len(pool1) == 1 || len(pool1) == 2 {
  86. check = true
  87. if len(pool1) == 1 {
  88. pool[1], _ = strconv.Atoi(pool1[0])
  89. pool[0] = int(math.Ceil(float64(pool[1]) * 0.2))
  90. } else {
  91. pool[0], _ = strconv.Atoi(pool1[0])
  92. pool[1], _ = strconv.Atoi(pool1[1])
  93. }
  94. } else {
  95. check = false
  96. }
  97. //解析最大空闲时间配置
  98. if len(arr) > 4-index {
  99. idle, _ = strconv.Atoi(arr[4-index])
  100. if idle == 0 {
  101. idle = 300
  102. }
  103. }
  104. }
  105. }
  106. }
  107. } else if _, ok := opt.(map[string]interface{}); ok {
  108. }
  109. if check {
  110. log.Println("代码 地址 []库范围 []池配置 空闲时间", code, addr, dbs, pool, idle)
  111. addrs := strings.Split(addr, "|") //备用节点模式
  112. if len(addrs) == 2 { //备用节点的模式 2选1
  113. r.init(addrs[0], code, dbs, pool[1], pool[0], idle)
  114. r.BakDb = true
  115. //有备用节点,集群先不考虑,支持指定的库
  116. addr1 := strings.Split(addrs[1], "/")
  117. r.Bak = &GoRedis{}
  118. if len(addr1) == 2 { //没有指定库 根据/区分
  119. i, _ := strconv.Atoi(addr1[1])
  120. dbs = []int{i}
  121. }
  122. r.Bak.init(addr1[0], code, dbs, pool[1], pool[0], idle)
  123. } else if len(addrs) == 1 {
  124. addr1 := strings.Split(addrs[0], "#") //是多节点模式,所有库默认为0
  125. if len(addr1) == 1 {
  126. r.init(addr1[0], code, dbs, pool[1], pool[0], idle)
  127. } else { //多节点模式
  128. r.Code = code
  129. r.HashDb = 1 + len(dbs)
  130. if len(dbs) > 1 {
  131. r.DBS = []int{}
  132. for i := dbs[0]; i <= dbs[1]; i++ {
  133. r.DBS = append(r.DBS, i)
  134. }
  135. } else {
  136. r.DBS = dbs
  137. }
  138. r.DB = dbs[0]
  139. r.Ctx = context.Background()
  140. r.CMap = map[int]map[int]*redis.Client{}
  141. r.Nodes = []int{}
  142. for i := 0; i < len(addr1); i++ {
  143. r.Nodes = append(r.Nodes, i)
  144. r.CMap[i] = map[int]*redis.Client{}
  145. for k, v := range r.DBS { //按节点的每个库初始化
  146. r.CMap[i][k] = redis.NewClient(&redis.Options{
  147. Addr: addr1[i],
  148. DB: v,
  149. PoolSize: pool[1],
  150. MinIdleConns: pool[0],
  151. IdleTimeout: time.Duration(idle) * time.Second,
  152. })
  153. }
  154. }
  155. }
  156. }
  157. }
  158. log.Println(check, code, addr, dbs, pool, idle, r.DBS)
  159. }
  160. //初始化连接
  161. func (r *GoRedis) init(addr, code string, dbs []int, poolSize, minIdleConns, idleTimeOut int) {
  162. r.Code = code
  163. r.DB = dbs[0]
  164. r.Ctx = context.Background()
  165. r.CMap = map[int]map[int]*redis.Client{}
  166. r.CMap[0] = map[int]*redis.Client{}
  167. if len(dbs) > 1 {
  168. r.HashDb = len(dbs) - 1
  169. r.DBS = []int{}
  170. for i := dbs[0]; i <= dbs[1]; i++ {
  171. r.DBS = append(r.DBS, i)
  172. }
  173. } else {
  174. r.DBS = dbs
  175. }
  176. for k, v := range r.DBS { //按节点的每个库初始化
  177. r.CMap[0][k] = redis.NewClient(&redis.Options{
  178. Addr: addr,
  179. DB: v,
  180. PoolSize: poolSize,
  181. MinIdleConns: minIdleConns,
  182. IdleTimeout: time.Duration(idleTimeOut) * time.Second,
  183. })
  184. }
  185. }
  186. //int转timeDuration
  187. func D(t int) time.Duration {
  188. return time.Duration(t) * time.Second
  189. }
  190. //取db
  191. func (r *GoRedis) GetDB(key string) (int, int) {
  192. switch r.HashDb {
  193. case 0: //单节点单库
  194. return 0, 0
  195. case 1: //单节点多库
  196. return 0, hashCode(key) % len(r.DBS)
  197. case 2: //多节点单库
  198. return hashCode(key[len(key)/2:]) % len(r.Nodes), 0
  199. case 3: ////多节点多库
  200. return hashCode(key[len(key)/2:]) % len(r.Nodes), hashCode(key) % len(r.DBS)
  201. }
  202. // if r.HashDb {
  203. // //return int(key[len(key)-1]) % len(r.DBS)
  204. // return hashCode(key) % len(r.DBS)
  205. // } else {
  206. // return r.DB
  207. // }
  208. return 0, 0
  209. }
  210. //根据key取hash
  211. func hashCode(key string) int {
  212. v := int(crc32.ChecksumIEEE([]byte(key)))
  213. if v < 0 {
  214. v = -v
  215. }
  216. return v
  217. }
  218. func (r *GoRedis) Client(key string) *redis.Client {
  219. _i, _k := r.GetDB(key)
  220. m := r.CMap[_i]
  221. if m != nil {
  222. c := m[_k]
  223. if c != nil {
  224. return c
  225. }
  226. }
  227. return &redis.Client{}
  228. }
  229. //-----具体方法
  230. //简单的Put方法
  231. func (r *GoRedis) Put(key string, val interface{}) (string, error) {
  232. stutsCmd := r.Client(key).Set(r.Ctx, key, val, 0)
  233. str, err := stutsCmd.Result()
  234. return str, err
  235. }
  236. //存key,加过期时间
  237. func (r *GoRedis) Set(key string, val interface{}, timeout int) (string, error) {
  238. stutsCmd := r.Client(key).Set(r.Ctx, key, val, D(timeout))
  239. //cmd := r.CMap[r.GetDB(key)].Do(r.Ctx, "setex", key, timeout, val)
  240. str, err := stutsCmd.Result()
  241. return str, err
  242. }
  243. //简单的Get方法,无结果返回空串,err: redis: nil
  244. func (r *GoRedis) Get(key string) (string, error) {
  245. stutsCmd := r.Client(key).Get(r.Ctx, key)
  246. str, err := stutsCmd.Result()
  247. // log.Println("1", str, "-", err)
  248. if err != nil {
  249. //有备用节点
  250. if r.BakDb {
  251. str, err = r.Bak.Get(key)
  252. }
  253. }
  254. return str, err
  255. }
  256. //根据正则取key,未考虑负载、多库
  257. func (r *GoRedis) GetByPattern(key string) (res []string, err error) {
  258. serr := ""
  259. for _, v1 := range r.CMap {
  260. for _, v := range v1 {
  261. strSlice := v.Keys(r.Ctx, key)
  262. arr, err1 := strSlice.Result()
  263. if len(arr) > 0 {
  264. res = append(res, arr...)
  265. } else if err1 != nil {
  266. serr += err1.Error()
  267. }
  268. }
  269. }
  270. if serr != "" {
  271. err = errors.New(serr)
  272. }
  273. return
  274. }
  275. //批量保存数据
  276. // 不支持- MSet("key1", "value1", "key2", "value2")
  277. // 不支持- MSet([]string{"key1", "value1", "key2", "value2"})
  278. // []interface{[]interface{k1,v1},[]interface{k2,v2},[]interface{k3,v3} }
  279. // - MSet(map[string]interface{}{"key1": "value1", "key2": "value2"})
  280. func (r *GoRedis) BulkPut(timeout int, obj interface{}) {
  281. if r.HashDb > 0 {
  282. if timeout < 1 {
  283. timeout = 0
  284. }
  285. timeEx := time.Duration(timeout) * time.Second
  286. switch obj.(type) {
  287. case []interface{}:
  288. if objs, ok := obj.([]interface{}); ok {
  289. for _, _tmp := range objs {
  290. tmp, ok := _tmp.([]interface{})
  291. if ok && len(tmp) == 2 {
  292. key, ok1 := tmp[0].(string)
  293. if ok1 {
  294. r.Client(key).Set(r.Ctx, key, tmp[1], timeEx)
  295. }
  296. }
  297. }
  298. }
  299. case map[string]interface{}:
  300. if objs, ok := obj.(map[string]interface{}); ok {
  301. for k, v := range objs {
  302. r.Client(k).Set(r.Ctx, k, v, timeEx)
  303. }
  304. }
  305. }
  306. } else {
  307. //单库直接保存
  308. if timeout < 1 {
  309. stutsCmd := r.CMap[0][0].MSet(r.Ctx, obj)
  310. str, err := stutsCmd.Result()
  311. log.Println(str, err)
  312. } else {
  313. timeEx := time.Duration(timeout) * time.Second
  314. //设置超时
  315. lenth := 0
  316. cmds, err := r.CMap[0][0].Pipelined(r.Ctx, func(pipe redis.Pipeliner) error {
  317. if objs, ok := obj.([]interface{}); ok {
  318. lenth = len(objs)
  319. for _, _tmp := range objs {
  320. tmp, ok := _tmp.([]interface{})
  321. if ok && len(tmp) == 2 {
  322. key, ok1 := tmp[0].(string)
  323. if ok1 {
  324. pipe.Set(r.Ctx, key, tmp[1], timeEx)
  325. }
  326. }
  327. }
  328. } else if objs, ok := obj.(map[string]interface{}); ok {
  329. lenth = len(objs)
  330. for k, v := range objs {
  331. pipe.Set(r.Ctx, k, v, timeEx)
  332. }
  333. } else {
  334. log.Println("bulkPut type error")
  335. }
  336. return nil
  337. })
  338. if err != nil {
  339. log.Println("bulkPut error", err.Error())
  340. }
  341. if len(cmds) == lenth { //数据相等
  342. for _, v := range cmds {
  343. log.Println("cmd", v.Args(), v.String())
  344. }
  345. }
  346. }
  347. }
  348. }
  349. //设置超时时间,单位秒
  350. func (r *GoRedis) SetExpire(key string, expire int) error {
  351. boolCmd := r.Client(key).Expire(r.Ctx, key, D(expire))
  352. return boolCmd.Err()
  353. }
  354. //判断一个key是否存在
  355. func (r *GoRedis) Exists(key string) bool {
  356. intCmd := r.Client(key).Exists(r.Ctx, key)
  357. i, err := intCmd.Result()
  358. if err != nil {
  359. log.Println("redisutil-exists", key, err)
  360. }
  361. return i == 1
  362. }
  363. //直接返回字节流
  364. func (r *GoRedis) GetBytes(key string) (ret *[]byte, err error) {
  365. cmd := r.Client(key).Do(r.Ctx, "GET", key)
  366. res, err := cmd.Result()
  367. log.Println(res)
  368. if err != nil {
  369. log.Println("redisutil-GetBytesError", err)
  370. } else {
  371. if tmp, ok := res.([]byte); ok {
  372. ret = &tmp
  373. } else if tmp, ok := res.(string); ok {
  374. bs := []byte(tmp)
  375. ret = &bs
  376. } else {
  377. err = errors.New("redis返回数据格式不对")
  378. }
  379. }
  380. return
  381. }
  382. //支持删除多个key
  383. func (r *GoRedis) Del(key ...string) (b bool) {
  384. i := 0
  385. if r.HashDb > 0 {
  386. for _, k := range key {
  387. cmd := r.Client(k).Del(r.Ctx, k)
  388. i1, _ := cmd.Result()
  389. i += int(i1)
  390. }
  391. } else {
  392. intCmd := r.CMap[0][0].Del(r.Ctx, key...)
  393. i1, _ := intCmd.Result()
  394. i = int(i1)
  395. }
  396. return i == len(key)
  397. }
  398. //根据代码和前辍key删除多个
  399. func (r *GoRedis) DelByPattern(key string) {
  400. res, _ := r.GetByPattern(key)
  401. if len(res) > 0 {
  402. r.Del(res...)
  403. }
  404. }
  405. //自增计数器
  406. func (r *GoRedis) Incr(key string) (int64, error) {
  407. intCmd := r.Client(key).Incr(r.Ctx, key)
  408. i, err := intCmd.Result()
  409. return i, err
  410. }
  411. //自减
  412. func (r *GoRedis) Decrby(key string, val int) (int64, error) {
  413. intCmd := r.Client(key).DecrBy(r.Ctx, key, int64(val))
  414. i, err := intCmd.Result()
  415. return i, err
  416. }
  417. //批量取多个key
  418. func (r *GoRedis) Mget(key []string) []interface{} {
  419. if r.HashDb > 0 {
  420. mdb := map[int]map[int][]string{}
  421. for _, v := range key { //分组
  422. _i, _k := r.GetDB(v)
  423. mdb[_i] = map[int][]string{}
  424. arr := mdb[_i][_k]
  425. if arr == nil {
  426. arr = []string{v}
  427. } else {
  428. arr = append(arr, v)
  429. }
  430. mdb[_i][_k] = arr
  431. }
  432. res := []interface{}{}
  433. for k, v := range mdb {
  434. for k1, v1 := range v {
  435. sliceCmd := r.CMap[k][k1].MGet(r.Ctx, v1...)
  436. res1, err := sliceCmd.Result()
  437. if err != nil {
  438. log.Println("Mget error", err)
  439. }
  440. res = append(res, res1...)
  441. }
  442. }
  443. return res
  444. } else {
  445. sliceCmd := r.CMap[0][0].MGet(r.Ctx, key...)
  446. res, err := sliceCmd.Result()
  447. if err != nil {
  448. log.Println("Mget error", err)
  449. }
  450. return res
  451. }
  452. }
  453. //取出并删除Key
  454. func (r *GoRedis) Pop(key string) (result interface{}) {
  455. c := r.Client(key)
  456. strCmd := c.Get(r.Ctx, key)
  457. b, err := strCmd.Bytes()
  458. if err != nil {
  459. log.Println("Poperr bytes", err)
  460. return
  461. }
  462. err1 := json.Unmarshal(b, &result)
  463. if err1 != nil {
  464. log.Println("Poperr json ", err)
  465. return
  466. } else {
  467. go c.Del(r.Ctx, key)
  468. }
  469. return
  470. }
  471. //list操作
  472. func (r *GoRedis) LPOP(list string) (result interface{}) {
  473. strCmd := r.Client(list).LPop(r.Ctx, list)
  474. b, err := strCmd.Bytes()
  475. if err != nil {
  476. log.Println("LPOP bytes", err)
  477. return
  478. }
  479. err1 := json.Unmarshal(b, &result)
  480. if err1 != nil {
  481. log.Println("LPOP json ", err)
  482. return
  483. }
  484. return
  485. }
  486. //将一个或多个值插入到列表的尾部
  487. func (r *GoRedis) RPUSH(list string, val ...interface{}) bool {
  488. intCmd := r.Client(list).RPush(r.Ctx, list, val...)
  489. i, err := intCmd.Result()
  490. if err != nil {
  491. log.Println("RPUSH bytes", err)
  492. return false
  493. }
  494. return i == 1
  495. }
  496. //获取列表长度
  497. func (r *GoRedis) LLEN(list string) int64 {
  498. intCmd := r.Client(list).LLen(r.Ctx, list)
  499. i, err := intCmd.Result()
  500. if err != nil {
  501. log.Println("RPUSH bytes", err)
  502. }
  503. return i
  504. }