Producer

  1. package kafka
  2. import (
  3. "context"
  4. "encoding/json"
  5. "github.com/Shopify/sarama"
  6. )
  7. // @Author Chen Zikang
  8. // @Email zikang.chen@shopee.com
  9. // @Since 2022-04-15
  10. // Producer defines interface for a kafka producer
  11. type Producer interface {
  12. SendMessage(ctx context.Context, key *string, value interface{}) error
  13. Topic() string
  14. Close() error
  15. }
  16. // producerImpl implements Producer
  17. type producerImpl struct {
  18. producer sarama.SyncProducer
  19. topic string
  20. }
  21. // NewKafkaProducer create a new kafka producer
  22. func NewKafkaProducer(topic string, brokers []string, config *sarama.Config) (Producer, error) {
  23. producer, err := sarama.NewSyncProducer(brokers, config)
  24. if err != nil {
  25. return nil, err
  26. }
  27. return &producerImpl{producer: producer, topic: topic}, nil
  28. }
  29. // SendMessage sends a message with key and value
  30. func (p *producerImpl) SendMessage(ctx context.Context, key *string, value interface{}) error {
  31. encodedValue, err := json.Marshal(value)
  32. if err != nil {
  33. return err
  34. }
  35. msg := &sarama.ProducerMessage{
  36. Topic: p.topic,
  37. Partition: -1,
  38. Value: sarama.ByteEncoder(encodedValue),
  39. }
  40. if key != nil {
  41. msg.Key = sarama.ByteEncoder([]byte(*key))
  42. }
  43. _, _, err = p.producer.SendMessage(msg)
  44. if err != nil {
  45. return err
  46. }
  47. return nil
  48. }
  49. func (p *producerImpl) Topic() string {
  50. return p.topic
  51. }
  52. func (p *producerImpl) Close() error {
  53. return p.producer.Close()
  54. }

Consumer

  1. package kafka
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "os"
  7. "os/signal"
  8. "sync"
  9. "syscall"
  10. "time"
  11. "github.com/Shopify/sarama"
  12. "gopkg.in/errgo.v2/errors"
  13. )
  14. // @Author Chen Zikang
  15. // @Email zikang.chen@shopee.com
  16. // @Since 2022-04-15
  17. // Consumer defines interface for a kafka consumer
  18. type Consumer interface {
  19. Start(ctx context.Context) error
  20. Setup(session sarama.ConsumerGroupSession) error
  21. Cleanup(session sarama.ConsumerGroupSession) error
  22. ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error
  23. InfoChannel() <-chan string
  24. ErrorChannel() <-chan error
  25. }
  26. // MessageHandler signature for kafka message handler function
  27. type MessageHandler func(ctx context.Context, message *sarama.ConsumerMessage) error
  28. // consumerImpl implements
  29. type consumerImpl struct {
  30. topics []string
  31. consumerGroup sarama.ConsumerGroup
  32. handler MessageHandler
  33. retryConfig RetryConfig
  34. infoChannel chan string
  35. errorChannel chan error
  36. ready chan bool
  37. }
  38. // RetryConfig consumer's retry config
  39. type RetryConfig struct {
  40. EnableRetry bool
  41. MaximumRetryTime int
  42. InitialDelayTime time.Duration
  43. MaximumDelayTime time.Duration
  44. }
  45. // NewKafkaConsumer create a new kafka consumer
  46. func NewKafkaConsumer(topics []string, brokers []string, consumerGroupName string,
  47. config *sarama.Config, handler MessageHandler, retryConfig RetryConfig) (Consumer, error) {
  48. consumer := &consumerImpl{
  49. topics: topics,
  50. handler: handler,
  51. retryConfig: retryConfig,
  52. ready: make(chan bool),
  53. infoChannel: make(chan string, 1),
  54. errorChannel: make(chan error, 1),
  55. }
  56. consumerGroup, err := sarama.NewConsumerGroup(brokers, consumerGroupName, config)
  57. if err != nil {
  58. return nil, err
  59. }
  60. consumer.consumerGroup = consumerGroup
  61. return consumer, nil
  62. }
  63. // Start set up a new sarama consumer group
  64. func (c *consumerImpl) Start(ctx context.Context) error {
  65. ctx, cancel := context.WithCancel(ctx)
  66. wg := &sync.WaitGroup{}
  67. wg.Add(1)
  68. go func() {
  69. defer wg.Done()
  70. if err := c.consumerGroup.Consume(ctx, c.topics, c); err != nil {
  71. logError(c.errorChannel, errors.New("consumer error"))
  72. }
  73. if ctx.Err() != nil {
  74. return
  75. }
  76. c.ready = make(chan bool)
  77. }()
  78. go func() {
  79. defer wg.Done()
  80. c.listenLog()
  81. }()
  82. // NOTE <-r.ready will block util close(c.ready)
  83. <-c.ready // wait till the consumer has been set up
  84. logInfo(c.infoChannel, fmt.Sprintf("sarama consumer up for topics %v up and running", c.topics))
  85. sigterm := make(chan os.Signal, 1)
  86. signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM)
  87. select {
  88. case <-ctx.Done():
  89. logInfo(c.infoChannel, fmt.Sprintf("terminating: context cancel"))
  90. case <-sigterm:
  91. logInfo(c.infoChannel, fmt.Sprintf("terminating: via signal"))
  92. }
  93. cancel()
  94. wg.Wait()
  95. if err := c.consumerGroup.Close(); err != nil {
  96. logInfo(c.infoChannel, fmt.Sprintf("close consumer group"))
  97. return err
  98. }
  99. return nil
  100. }
  101. // Setup is run at the beginning of a new session, before ConsumeClaim
  102. func (c *consumerImpl) Setup(session sarama.ConsumerGroupSession) error {
  103. close(c.ready)
  104. return nil
  105. }
  106. // Cleanup is run at the end of a session, once all ConsumeClaim goroutines have exited
  107. func (c *consumerImpl) Cleanup(session sarama.ConsumerGroupSession) error {
  108. return nil
  109. }
  110. // ConsumeClaim must start a consumer loop of ConsumerGroupClaim's Messages()
  111. func (c *consumerImpl) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
  112. for message := range claim.Messages() {
  113. if message == nil {
  114. continue
  115. }
  116. logInfo(c.infoChannel, fmt.Sprintf("processing message: %v", string(message.Value)))
  117. c.withBackoff(func() error {
  118. return c.handler(session.Context(), message)
  119. }, c.retryConfig)
  120. }
  121. return nil
  122. }
  123. func (c *consumerImpl) InfoChannel() <-chan string {
  124. return c.infoChannel
  125. }
  126. func (c *consumerImpl) ErrorChannel() <-chan error {
  127. return c.errorChannel
  128. }
  129. func (c *consumerImpl) listenLog() {
  130. for {
  131. select {
  132. case info := <-c.infoChannel:
  133. log.Println("[INFO] ", info)
  134. case err := <-c.errorChannel:
  135. log.Println("[ERROR]", err)
  136. }
  137. }
  138. }
  139. func (c *consumerImpl) withBackoff(f func() error, retryConfig RetryConfig) {
  140. if !retryConfig.EnableRetry {
  141. if err := c.runFunctionAndCapturePanic(f); err != nil {
  142. logError(c.errorChannel, errors.New("run function"))
  143. }
  144. return
  145. }
  146. delayTime := retryConfig.InitialDelayTime
  147. for i := 0; i < retryConfig.MaximumRetryTime+1; i++ {
  148. if err := c.runFunctionAndCapturePanic(f); err != nil {
  149. logError(c.errorChannel, errors.New("run function"))
  150. time.Sleep(delayTime)
  151. delayTime = delayTime << 1
  152. if delayTime > retryConfig.MaximumDelayTime {
  153. delayTime = retryConfig.MaximumDelayTime
  154. }
  155. continue
  156. }
  157. return
  158. }
  159. }
  160. func (c *consumerImpl) runFunctionAndCapturePanic(f func() error) (err error) {
  161. defer func() {
  162. if r := recover(); r != nil {
  163. err = errors.New("no retry")
  164. }
  165. }()
  166. return f()
  167. }

Test

  1. package kafka
  2. import (
  3. "context"
  4. "log"
  5. "testing"
  6. "time"
  7. "github.com/Shopify/sarama"
  8. )
  9. // @Author Chen Zikang
  10. // @Email zikang.chen@shopee.com
  11. // @Since 2022-05-08
  12. func StringMessageHandler(ctx context.Context, message *sarama.ConsumerMessage) error {
  13. log.Printf("Consume message: offset=%v, key=%v, value=%v\n", message.Offset, string(message.Key), string(message.Value))
  14. return nil
  15. }
  16. func TestConsumer(t *testing.T) {
  17. var (
  18. brokerList = []string{"127.0.0.1:9092"}
  19. topicList = []string{"hello-1"}
  20. consumerGroupName = "test"
  21. )
  22. // config
  23. config := sarama.NewConfig()
  24. config.Version = sarama.V1_1_0_0
  25. config.ClientID = "KHighness"
  26. config.Producer.RequiredAcks = sarama.WaitForAll
  27. config.Producer.Return.Successes = true
  28. config.Producer.Retry.Max = 10
  29. config.Consumer.MaxProcessingTime = 1 * time.Hour
  30. // retry config
  31. retryConfig := RetryConfig{
  32. EnableRetry: true,
  33. MaximumRetryTime: 10,
  34. InitialDelayTime: 1 * time.Second,
  35. MaximumDelayTime: 5 * time.Minute,
  36. }
  37. consumer, err := NewKafkaConsumer(topicList, brokerList, consumerGroupName, config, StringMessageHandler, retryConfig)
  38. if err != nil {
  39. log.Fatalln(err)
  40. }
  41. ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
  42. defer cancel()
  43. log.Println("Consumer start successfully")
  44. err = consumer.Start(ctx)
  45. if err != nil {
  46. log.Fatalln(err)
  47. }
  48. }
  1. package kafka
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "testing"
  7. "time"
  8. "github.com/Shopify/sarama"
  9. )
  10. // @Author Chen Zikang
  11. // @Email zikang.chen@shopee.com
  12. // @Since 2022-05-08
  13. func TestProducer(t *testing.T) {
  14. var brokerList = []string{"127.0.0.1:9092"}
  15. // config
  16. config := sarama.NewConfig()
  17. config.Version = sarama.V1_1_0_0
  18. config.ClientID = "KHighness"
  19. config.Producer.RequiredAcks = sarama.WaitForAll
  20. config.Producer.Return.Successes = true
  21. config.Producer.Retry.Max = 10
  22. config.Consumer.MaxProcessingTime = 1 * time.Hour
  23. producer, err := NewKafkaProducer("hello-1", brokerList, config)
  24. if err != nil {
  25. log.Fatalln(err)
  26. }
  27. for i := 0; i < 5; i++ {
  28. key := fmt.Sprintf("%d", i)
  29. producer.SendMessage(context.Background(), &key, "KHighness")
  30. }
  31. }