redis.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/cache/redis"
  6. "go-common/library/log"
  7. )
  8. const (
  9. _keyWaitBlock = "wb_" // b_batch_no wait block
  10. _preLock = "lk_"
  11. )
  12. // keyWaitBlock return block cache key.
  13. func keyWaitBlock(batchNo int64) string {
  14. return _keyWaitBlock + fmt.Sprintf("%d", batchNo)
  15. }
  16. func lockKey(key int64) string {
  17. return fmt.Sprintf("%s%d", _preLock, key)
  18. }
  19. // AddBlockCache add block cache.
  20. func (d *Dao) AddBlockCache(c context.Context, mid int64, score int8, blockNo int64) (err error) {
  21. var (
  22. key = keyWaitBlock(blockNo)
  23. )
  24. conn := d.redis.Get(c)
  25. defer conn.Close()
  26. if err = conn.Send("ZADD", key, score, mid); err != nil {
  27. log.Error("conn.Send(ZADD %s,%d,%d) error(%v)", key, score, mid, err)
  28. return
  29. }
  30. if err = conn.Send("EXPIRE", key, d.expire); err != nil {
  31. log.Error("conn.Send(EXPIRE) error(%v)", err)
  32. return
  33. }
  34. if err = conn.Flush(); err != nil {
  35. log.Error("conn.Flush() error(%v)", err)
  36. return
  37. }
  38. for i := 0; i < 2; i++ {
  39. if _, err = conn.Receive(); err != nil {
  40. log.Error("conn.Receive() error(%v)", err)
  41. return
  42. }
  43. }
  44. return
  45. }
  46. // BlockMidCache get wait block mids.
  47. func (d *Dao) BlockMidCache(c context.Context, batchNo int64, num int64) (res []int64, err error) {
  48. var (
  49. conn = d.redis.Get(c)
  50. key = keyWaitBlock(batchNo)
  51. )
  52. defer conn.Close()
  53. if res, err = redis.Int64s(conn.Do("ZREVRANGEBYSCORE", key, "+inf", "-inf", "LIMIT", 0, num)); err != nil {
  54. log.Error("redis(ZREVRANGEBYSCORE %s,%d) error(%v)", key, num, err)
  55. return
  56. }
  57. return
  58. }
  59. //SetNXLockCache redis lock.
  60. func (d *Dao) SetNXLockCache(c context.Context, k int64) (res bool, err error) {
  61. var (
  62. key = lockKey(k)
  63. conn = d.redis.Get(c)
  64. )
  65. defer conn.Close()
  66. if res, err = redis.Bool(conn.Do("SETNX", key, "1")); err != nil {
  67. if err == redis.ErrNil {
  68. err = nil
  69. } else {
  70. log.Error("conn.Do(SETNX(%d)) error(%v)", key, err)
  71. return
  72. }
  73. }
  74. if res {
  75. if _, err = redis.Bool(conn.Do("EXPIRE", key, d.verifyExpire)); err != nil {
  76. log.Error("conn.Do(EXPIRE, %s, %d) error(%v)", key, d.verifyExpire, err)
  77. return
  78. }
  79. }
  80. return
  81. }
  82. // PingRedis check redis connection
  83. func (d *Dao) PingRedis(c context.Context) (err error) {
  84. conn := d.redis.Get(c)
  85. _, err = conn.Do("SET", "PING", "PONG")
  86. conn.Close()
  87. return
  88. }