service.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package offer
  2. import (
  3. "context"
  4. "strings"
  5. "sync"
  6. "time"
  7. "go-common/app/job/main/app-wall/conf"
  8. offerDao "go-common/app/job/main/app-wall/dao/offer"
  9. "go-common/app/job/main/app-wall/model/offer"
  10. "go-common/library/log"
  11. "github.com/Shopify/sarama"
  12. cluster "github.com/bsm/sarama-cluster"
  13. )
  14. // Service struct
  15. type Service struct {
  16. c *conf.Config
  17. dao *offerDao.Dao
  18. consumer *cluster.Consumer
  19. activeChan chan *offer.ActiveMsg
  20. closed bool
  21. waiter sync.WaitGroup
  22. }
  23. // New init
  24. func New(c *conf.Config) (s *Service) {
  25. s = &Service{
  26. c: c,
  27. dao: offerDao.New(c),
  28. activeChan: make(chan *offer.ActiveMsg, 10240),
  29. closed: false,
  30. }
  31. var err error
  32. if s.consumer, err = s.NewConsumer(); err != nil {
  33. log.Error("%+v", err)
  34. panic(err)
  35. }
  36. s.waiter.Add(1)
  37. go s.activeConsumer()
  38. s.waiter.Add(1)
  39. go s.activeproc()
  40. // retry consumer
  41. for i := 0; i < 4; i++ {
  42. s.waiter.Add(1)
  43. go s.retryproc()
  44. }
  45. return s
  46. }
  47. // Ping Service
  48. func (s *Service) Ping(c context.Context) (err error) {
  49. return s.dao.Ping(c)
  50. }
  51. // Close Service
  52. func (s *Service) Close() {
  53. s.closed = true
  54. s.consumer.Close()
  55. s.waiter.Wait()
  56. log.Info("app-wall-job closed.")
  57. }
  58. // NewConsumer new cluster consumer.
  59. func (s *Service) NewConsumer() (*cluster.Consumer, error) {
  60. // cluster config
  61. cfg := cluster.NewConfig()
  62. // NOTE cluster auto commit offset interval
  63. cfg.Consumer.Offsets.CommitInterval = time.Second * 1
  64. // NOTE set fetch.wait.max.ms
  65. cfg.Consumer.MaxWaitTime = time.Millisecond * 100
  66. // NOTE errors that occur during offset management,if enabled, c.Errors channel must be read
  67. cfg.Consumer.Return.Errors = true
  68. // NOTE notifications that occur during consumer, if enabled, c.Notifications channel must be read
  69. cfg.Group.Return.Notifications = true
  70. // The initial offset to use if no offset was previously committed.
  71. // default: OffsetOldest
  72. if strings.ToLower(s.c.Consumer.Offset) != "new" {
  73. cfg.Consumer.Offsets.Initial = sarama.OffsetOldest
  74. } else {
  75. cfg.Consumer.Offsets.Initial = sarama.OffsetNewest
  76. }
  77. // new cluster consumer
  78. log.Info("s.c.Consumer.Brokers: %v", s.c.Consumer.Brokers)
  79. return cluster.NewConsumer(s.c.Consumer.Brokers, s.c.Consumer.Group, []string{s.c.Consumer.Topic}, cfg)
  80. }