task.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package redis
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "time"
  7. "go-common/app/admin/main/aegis/model/common"
  8. modtask "go-common/app/admin/main/aegis/model/task"
  9. "go-common/library/cache/redis"
  10. "go-common/library/log"
  11. "github.com/pkg/errors"
  12. )
  13. /*
  14. 四个缓存
  15. 1. personalPool 存储每个用户的任务池 类型为List []taskid
  16. 2. publicPool 存储还未被领取的任务 类型为Sorted Set weight-taskid
  17. 3. delayPool 存储每个用户的延迟任务 类型为List
  18. 4. hashTask 存储所有任务的所有其他字段信息
  19. */
  20. const (
  21. _hashexpire = 24 * 60 * 60
  22. )
  23. func personalKey(businessID, flowID int64, uid int64) string {
  24. return fmt.Sprintf("personal_%d_%d_%d", businessID, flowID, uid)
  25. }
  26. func publicKey(businessID, flowID int64) string {
  27. return fmt.Sprintf("{%d-%d}public_%d_%d", businessID, flowID, businessID, flowID)
  28. }
  29. func delayKey(businessID, flowID int64, uid int64) string {
  30. return fmt.Sprintf("delay_%d_%d_%d", businessID, flowID, uid)
  31. }
  32. func haskKey(taskid int64) string {
  33. return fmt.Sprintf("task_%d", taskid)
  34. }
  35. // formatID 在sorted set里面,id要扩展出来,否则排序不对
  36. func formatID(taskid int64) string {
  37. return fmt.Sprintf("%.11d", taskid)
  38. }
  39. // CountPersonalTask 统计个数
  40. func (d *Dao) CountPersonalTask(c context.Context, opt *common.BaseOptions) (count int64, err error) {
  41. conn := d.cluster.Get(c)
  42. defer conn.Close()
  43. key := personalKey(opt.BusinessID, opt.FlowID, opt.UID)
  44. if count, err = redis.Int64(conn.Do("LLEN", key)); err != nil {
  45. log.Error("conn.Do(LLEN,%s) error(%v)", key, err)
  46. }
  47. return
  48. }
  49. // RangePersonalTask 从本人的任务池取
  50. func (d *Dao) RangePersonalTask(c context.Context, opt *modtask.ListOptions) (tasks map[int64]*modtask.Task, count int64, hitids, missids []int64, err error) {
  51. tasks, count, hitids, missids, err = d.rangefuncCluster(c, "personal", opt)
  52. return
  53. }
  54. // RangeDealyTask .
  55. func (d *Dao) RangeDealyTask(c context.Context, opt *modtask.ListOptions) (tasks map[int64]*modtask.Task, count int64, hitids, missids []int64, err error) {
  56. return d.rangefuncCluster(c, "delay", opt)
  57. }
  58. // RangePublicTask .
  59. func (d *Dao) RangePublicTask(c context.Context, opt *modtask.ListOptions) (tasks map[int64]*modtask.Task, count int64, hitids, missids []int64, err error) {
  60. return d.rangefuncCluster(c, "public", opt)
  61. }
  62. // PushPersonalTask 放入本人任务池
  63. func (d *Dao) PushPersonalTask(c context.Context, opt *common.BaseOptions, ids ...interface{}) (err error) {
  64. key := personalKey(opt.BusinessID, opt.FlowID, opt.UID)
  65. return d.pushList(c, key, ids...)
  66. }
  67. // RemovePersonalTask 任务延迟或完成
  68. func (d *Dao) RemovePersonalTask(c context.Context, opt *common.BaseOptions, ids ...interface{}) (err error) {
  69. key := personalKey(opt.BusinessID, opt.FlowID, opt.UID)
  70. return d.removeList(c, key, ids...)
  71. }
  72. // RemoveDelayTask 延迟任务完成
  73. func (d *Dao) RemoveDelayTask(c context.Context, opt *common.BaseOptions, ids ...interface{}) (err error) {
  74. key := delayKey(opt.BusinessID, opt.FlowID, opt.UID)
  75. return d.removeList(c, key, ids...)
  76. }
  77. func (d *Dao) removeList(c context.Context, key string, ids ...interface{}) (err error) {
  78. conn := d.cluster.Get(c)
  79. defer conn.Close()
  80. for _, id := range ids {
  81. if err = conn.Send("LREM", key, 1, id); err != nil {
  82. log.Error("LREM error(%v)", errors.WithStack(err))
  83. continue
  84. }
  85. }
  86. if err = conn.Flush(); err != nil {
  87. log.Error("Flush error(%v)", errors.WithStack(err))
  88. return
  89. }
  90. for i := 0; i < len(ids); i++ {
  91. if _, err = conn.Receive(); err != nil {
  92. log.Error("Receive error(%v)", errors.WithStack(err))
  93. return
  94. }
  95. }
  96. return
  97. }
  98. // Release 清空个人任务 直接删除key
  99. func (d *Dao) Release(c context.Context, opt *common.BaseOptions, delay bool) (err error) {
  100. var conn = d.cluster.Get(c)
  101. defer conn.Close()
  102. key := personalKey(opt.BusinessID, opt.FlowID, opt.UID)
  103. log.Info("Redis Release(%+v) delay(%v)", opt, delay)
  104. if delay {
  105. debug := func(msg string) {
  106. tasks, count, hitids, missids, err1 := d.rangefuncCluster(c, "personal", &modtask.ListOptions{
  107. BaseOptions: *opt,
  108. Pager: common.Pager{
  109. Pn: 1,
  110. Ps: 10,
  111. },
  112. })
  113. for id, task := range tasks {
  114. log.Info(msg+" Release task(%d)(%+v)", id, task)
  115. }
  116. log.Info(msg+" Release count(%d)", count)
  117. log.Info(msg+" Release hitids(%+v)", hitids)
  118. log.Info(msg+" Release missids(%+v)", missids)
  119. log.Info(msg+" Release err(%+v)", err1)
  120. }
  121. debug("Before")
  122. if _, err = conn.Do("LTRIM", key, 0, 0); err != nil {
  123. log.Error("LTRIM ReleasePersonalTask(%s), error(%v)", key, err)
  124. }
  125. debug("Middle")
  126. time.AfterFunc(5*time.Minute, func() {
  127. d.Release(context.Background(), opt, false)
  128. })
  129. debug("After")
  130. } else {
  131. log.Info("Redis DEL Release(%+v) delay(%v)", opt, delay)
  132. if _, err = conn.Do("DEL", key); err != nil {
  133. log.Error("DEL ReleasePersonalTask(%s), error(%v)", key, err)
  134. }
  135. }
  136. return
  137. }
  138. // PushDelayTask 延迟任务队列
  139. func (d *Dao) PushDelayTask(c context.Context, opt *common.BaseOptions, ids ...interface{}) (err error) {
  140. key := delayKey(opt.BusinessID, opt.FlowID, opt.UID)
  141. return d.pushList(c, key, ids...)
  142. }
  143. func (d *Dao) pushList(c context.Context, key string, values ...interface{}) (err error) {
  144. var (
  145. conn = d.cluster.Get(c)
  146. )
  147. defer conn.Close()
  148. for _, id := range values {
  149. if _, err = conn.Do("LREM", key, 0, id); err != nil {
  150. log.Error("conn.Do(LREM, %v, %v, %v) error(%v)", key, 0, id, err)
  151. return
  152. }
  153. }
  154. args2 := []interface{}{key}
  155. args2 = append(args2, values...)
  156. if _, err = conn.Do("RPUSH", args2...); err != nil {
  157. log.Error("conn.Do(RPUSH, %v) error(%v)", args2, err)
  158. return
  159. }
  160. return
  161. }
  162. // RemovePublicTask 移除
  163. func (d *Dao) RemovePublicTask(c context.Context, opt *common.BaseOptions, ids ...interface{}) (err error) {
  164. conn := d.cluster.Get(c)
  165. defer conn.Close()
  166. key := publicKey(opt.BusinessID, opt.FlowID)
  167. args := []interface{}{key}
  168. nids := []interface{}{}
  169. for _, id := range ids {
  170. nids = append(nids, fmt.Sprintf("%.11d", id))
  171. }
  172. args = append(args, nids...)
  173. if _, err = conn.Do("ZREM", args...); err != nil {
  174. log.Error("(ZREM,%v) error(%v)", args, errors.WithStack(err))
  175. }
  176. return err
  177. }
  178. // PopPublicTask 从实时任务池取出来
  179. func (d *Dao) PopPublicTask(c context.Context, businessID, flowID, count int64) (ids []int64, err error) {
  180. conn := d.cluster.Get(c)
  181. defer conn.Close()
  182. key := publicKey(businessID, flowID)
  183. var tempids []int64
  184. if tempids, err = redis.Int64s(conn.Do("ZRANGE", key, 0, count)); err != nil {
  185. log.Error("conn.Do(ZADD,%s) error(%v)", key, errors.WithStack(err))
  186. }
  187. ids = append(ids, tempids...)
  188. return
  189. }
  190. // PushPublicTask 放入实时任务池
  191. func (d *Dao) PushPublicTask(c context.Context, tasks ...*modtask.Task) (err error) {
  192. conn := d.cluster.Get(c)
  193. defer conn.Close()
  194. for _, task := range tasks {
  195. key := publicKey(task.BusinessID, task.FlowID)
  196. id := formatID(task.ID)
  197. fmt.Println("id:", id)
  198. if _, err = conn.Do("ZADD", key, -task.Weight, id); err != nil {
  199. log.Error("conn.Do(ZADD,%s) error(%v)", key, errors.WithStack(err))
  200. }
  201. }
  202. return
  203. }
  204. // SetTask .
  205. func (d *Dao) SetTask(c context.Context, tasks ...*modtask.Task) (err error) {
  206. conn := d.cluster.Get(c)
  207. defer conn.Close()
  208. for _, task := range tasks {
  209. var bs []byte
  210. key := haskKey(task.ID)
  211. if bs, err = json.Marshal(task); err != nil {
  212. log.Error("json.Marshal(%+v) error(%v)", task, err)
  213. continue
  214. }
  215. if err = conn.Send("SET", key, bs); err != nil {
  216. log.Error("SET error(%v)", err)
  217. continue
  218. }
  219. if err = conn.Send("EXPIRE", key, _hashexpire); err != nil {
  220. log.Error("EXPIRE error(%v)", err)
  221. continue
  222. }
  223. }
  224. if err = conn.Flush(); err != nil {
  225. log.Error("conn.Flush error(%v)", err)
  226. return
  227. }
  228. for i := 0; i < 2*len(tasks); i++ {
  229. if _, err = conn.Receive(); err != nil {
  230. log.Error("conn.Receive error(%v)", err)
  231. return
  232. }
  233. }
  234. return
  235. }
  236. // GetTask .
  237. func (d *Dao) GetTask(c context.Context, ids []int64) (tasks []*modtask.Task, err error) {
  238. conn := d.cluster.Get(c)
  239. defer conn.Close()
  240. for _, id := range ids {
  241. key := haskKey(id)
  242. conn.Send("GET", key)
  243. }
  244. conn.Flush()
  245. var data []byte
  246. for i := 0; i < len(ids); i++ {
  247. if data, err = redis.Bytes(conn.Receive()); err != nil {
  248. log.Errorv(c, log.KV("event", "redis_get"), log.KV("key", haskKey(ids[i])), log.KV("error", err))
  249. return
  250. }
  251. task := new(modtask.Task)
  252. if err = json.Unmarshal(data, task); err != nil {
  253. log.Errorv(c, log.KV("event", "json.Unmarshal"), log.KV("task", string(data)), log.KV("error", err))
  254. return
  255. }
  256. tasks = append(tasks, task)
  257. }
  258. return
  259. }