redis_queue.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. package redis
  2. import (
  3. "git.aionnect.com/aionnect/go-common/utils"
  4. "git.aionnect.com/aionnect/go-common/utils/logger"
  5. "os"
  6. "os/signal"
  7. "strings"
  8. "syscall"
  9. "time"
  10. )
  11. // Redis队列实现
  12. // 注意! Redis Cluster不支持同时操作多个健的命令,例如BRPOPLPUSH",故本类与Redis Cluster不兼容
  13. type Queue struct {
  14. MainListName string // 主列表名称
  15. BackupListName string // 备份列表名称
  16. BlockedTimeout int // 阻塞超时
  17. RecycleTimeout time.Duration // 回收超时
  18. IsIdempotent bool // 是否幂等
  19. recycleTicker *time.Ticker // 回收定时器
  20. isRing bool // 是否环形队列
  21. hub *Hub // Redis连接适配器对象
  22. l *logger.Logger // 日志记录器实例
  23. }
  24. // 构造Redis队列新实例
  25. func NewRedisQueue(mainListName, backupListName string, blockedTimeout int, recycleTimeout time.Duration) *Queue {
  26. mainListName = strings.TrimSpace(mainListName)
  27. backupListName = strings.TrimSpace(backupListName)
  28. if mainListName == "" {
  29. mainListName = "defaultList"
  30. }
  31. if backupListName == "" {
  32. backupListName = mainListName
  33. }
  34. if blockedTimeout <= 0 {
  35. blockedTimeout = 500
  36. }
  37. if recycleTimeout <= 0 {
  38. recycleTimeout = 5 * time.Second
  39. }
  40. q := &Queue{
  41. hub: NewHub(),
  42. MainListName: mainListName,
  43. BackupListName: backupListName,
  44. BlockedTimeout: blockedTimeout,
  45. RecycleTimeout: recycleTimeout,
  46. }
  47. q.l = q.hub.LOG()
  48. q.isRing = q.MainListName == q.BackupListName
  49. // 自动关闭处理
  50. q.closeWait()
  51. return q
  52. }
  53. // Clean() 清理Redis列表,通常情况应该用不上
  54. func (q *Queue) Clean() {
  55. _, err := q.hub.Do("DEL", q.MainListName)
  56. if nil != err {
  57. q.l.Errorf("Clean() delete %s failed: %s", q.MainListName, err.Error())
  58. }
  59. if !q.isRing {
  60. _, err = q.hub.Do("DEL", q.BackupListName)
  61. if nil != err {
  62. q.l.Errorf("Clean() delete %s failed: %s", q.BackupListName, err.Error())
  63. }
  64. }
  65. }
  66. // Pop() 从Redis列表中读取数据
  67. // 为避免消费者崩溃或意外错误丢数据,被读取(主列表队尾)的数据同时插入(备份列表队头)备份列表,当成功处理完成时,再从备份列表移除
  68. // 备份列表和主列表可以是同一个,即构造一个环形队列,但注意在环形队列时,消费异常时的阻塞行为是有差异的,且数据积压少并有多个消费者时会触发重复处理
  69. func (q *Queue) Pop(fn func(interface{})) {
  70. for {
  71. reply, err := q.hub.Do("BRPOPLPUSH", q.MainListName, q.BackupListName, q.BlockedTimeout)
  72. if nil != err {
  73. q.l.Errorf("Pop() pop from %s and push to %s failed: %s", q.MainListName, q.BackupListName, err.Error())
  74. if err == ErrRedisConnNil { // Redis未连接时无阻塞,等待几秒再重试,以免死循环
  75. time.Sleep(5 * time.Second)
  76. }
  77. continue
  78. }
  79. if nil != fn {
  80. fn(reply)
  81. }
  82. // 环形队列时,为避免忽略掉新增的的相同内容更新事件,仅移除最新的一条与已处理值相等的内容
  83. // 当无新增的相同内容时,即刚刚RPOPLPUSH从队尾"备份"到队头的
  84. // 当有新增的相同内容时,虽然最新增加的一条会被移除,但队列中还是会有更早的"备份"记录
  85. pipeline := q.hub.Pipeline()
  86. if q.isRing {
  87. if q.IsIdempotent { // 当消息体是幂等时,即反复操作得到的结果一致时,当成功操作一次后,也即可清除主队列中相同元素,下同
  88. pipeline.Send("LREM", q.BackupListName, 0, reply) // isRing时BackupListName = MainListName
  89. } else {
  90. pipeline.Send("LREM", q.BackupListName, 1, reply)
  91. }
  92. } else { // 非环形队列时,移除备份列表中所有与已处理值相等的内容
  93. pipeline.Send("LREM", q.BackupListName, 0, reply)
  94. if q.IsIdempotent {
  95. pipeline.Send("LREM", q.MainListName, 0, reply)
  96. }
  97. }
  98. _, err = pipeline.Execute()
  99. if nil != err {
  100. q.l.Errorf("Pop() remove from %s failed: %s", q.BackupListName, err.Error())
  101. }
  102. }
  103. }
  104. // Push() 添加数据到Redis列表
  105. func (q *Queue) Push(obj interface{}) {
  106. _, err := q.hub.Do("LPUSH", q.MainListName, obj) // 主列表队头插入
  107. if nil != err {
  108. q.l.Errorf("Push() push to %s failed: %s", q.MainListName, err.Error())
  109. }
  110. }
  111. // recycle() 定时将备份队列中最早的一条内容,回收到主队列重试处理
  112. // 没有写到构造函数里,是为了可以灵活分离和分配生产者、消费者、回收者
  113. func (q *Queue) Recycle() {
  114. if q.isRing { // 环形队列不需要做回收处理
  115. return
  116. }
  117. go func(q *Queue) {
  118. defer utils.DefaultGoroutineRecover(nil, `Redis队列回收`)
  119. q.recycleTicker = time.NewTicker(q.RecycleTimeout)
  120. for {
  121. select {
  122. case <-q.recycleTicker.C:
  123. _, err := q.hub.Do("RPOPLPUSH", q.BackupListName, q.MainListName)
  124. if nil != err {
  125. q.l.Errorf("recycle() pop from %s and push to %s failed: %s", q.BackupListName, q.MainListName, err.Error())
  126. }
  127. }
  128. }
  129. }(q)
  130. }
  131. // 收到系统退出消息时自动关闭Redis队列相关资源
  132. func (q *Queue) closeWait() {
  133. go func(q *Queue) {
  134. defer utils.DefaultGoroutineRecover(nil, `Redis队列关闭`)
  135. var c chan os.Signal
  136. var s os.Signal
  137. c = make(chan os.Signal, 1)
  138. signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGKILL)
  139. for {
  140. s = <-c
  141. switch s {
  142. case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGKILL:
  143. if !q.isRing && nil != q.recycleTicker {
  144. q.recycleTicker.Stop()
  145. }
  146. err := q.hub.Close()
  147. if nil != err {
  148. q.l.Errorf("closeWait() close redis queue connection failed %s", err.Error())
  149. }
  150. return
  151. default:
  152. return
  153. }
  154. }
  155. }(q)
  156. }