cache_delay.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package service
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/job/main/member/model/queue"
  6. "go-common/library/log"
  7. )
  8. // Item is
  9. type Item struct {
  10. Mid int64
  11. Time time.Time
  12. Action string
  13. }
  14. // Compare is
  15. func (i *Item) Compare(other queue.Item) int {
  16. o := asItem(other)
  17. if o == nil {
  18. return -1
  19. }
  20. if i.Time.Equal(o.Time) {
  21. return 0
  22. }
  23. if i.Time.After(o.Time) {
  24. return 1
  25. }
  26. return -1
  27. }
  28. // HashCode is
  29. func (i *Item) HashCode() int64 {
  30. return i.Mid
  31. }
  32. func asItem(in queue.Item) *Item {
  33. o, ok := in.(*Item)
  34. if !ok {
  35. return nil
  36. }
  37. return o
  38. }
  39. func asItems(in []queue.Item) []*Item {
  40. out := make([]*Item, 0, len(in))
  41. for _, i := range in {
  42. item := asItem(i)
  43. if item == nil {
  44. continue
  45. }
  46. out = append(out, item)
  47. }
  48. return out
  49. }
  50. func (s *Service) cachedelayproc(ctx context.Context) {
  51. fiveSeconds := time.Second * 5
  52. t := time.NewTicker(fiveSeconds)
  53. delayed := func(t time.Time) bool {
  54. top := asItem(s.cachepq.Peek())
  55. if top == nil {
  56. log.Info("Empty cache queue top at: %v", t)
  57. return false
  58. }
  59. if t.Sub(top.Time) < fiveSeconds {
  60. log.Info("Top item is in five seconds, skip and waiting for next tick")
  61. return false
  62. }
  63. return true
  64. }
  65. for ti := range t.C {
  66. if !delayed(ti) {
  67. continue
  68. }
  69. for {
  70. qitems, err := s.cachepq.Get(1)
  71. if err != nil {
  72. log.Error("Failed to get queue items from cache queue: %+v", err)
  73. return
  74. }
  75. items := asItems(qitems)
  76. for _, it := range items {
  77. log.Info("Notify purge cache in delay queue with mid: %d", it.Mid)
  78. s.dao.NotifyPurgeCache(ctx, it.Mid, it.Action)
  79. }
  80. if s.cachepq.Empty() || !delayed(time.Now()) {
  81. break
  82. }
  83. }
  84. }
  85. }