Producer
package kafkaimport ( "context" "encoding/json" "github.com/Shopify/sarama")// @Author Chen Zikang// @Email zikang.chen@shopee.com// @Since 2022-04-15// Producer defines interface for a kafka producertype Producer interface { SendMessage(ctx context.Context, key *string, value interface{}) error Topic() string Close() error}// producerImpl implements Producertype producerImpl struct { producer sarama.SyncProducer topic string}// NewKafkaProducer create a new kafka producerfunc NewKafkaProducer(topic string, brokers []string, config *sarama.Config) (Producer, error) { producer, err := sarama.NewSyncProducer(brokers, config) if err != nil { return nil, err } return &producerImpl{producer: producer, topic: topic}, nil}// SendMessage sends a message with key and valuefunc (p *producerImpl) SendMessage(ctx context.Context, key *string, value interface{}) error { encodedValue, err := json.Marshal(value) if err != nil { return err } msg := &sarama.ProducerMessage{ Topic: p.topic, Partition: -1, Value: sarama.ByteEncoder(encodedValue), } if key != nil { msg.Key = sarama.ByteEncoder([]byte(*key)) } _, _, err = p.producer.SendMessage(msg) if err != nil { return err } return nil}func (p *producerImpl) Topic() string { return p.topic}func (p *producerImpl) Close() error { return p.producer.Close()}
Consumer
package kafkaimport ( "context" "fmt" "log" "os" "os/signal" "sync" "syscall" "time" "github.com/Shopify/sarama" "gopkg.in/errgo.v2/errors")// @Author Chen Zikang// @Email zikang.chen@shopee.com// @Since 2022-04-15// Consumer defines interface for a kafka consumertype Consumer interface { Start(ctx context.Context) error Setup(session sarama.ConsumerGroupSession) error Cleanup(session sarama.ConsumerGroupSession) error ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error InfoChannel() <-chan string ErrorChannel() <-chan error}// MessageHandler signature for kafka message handler functiontype MessageHandler func(ctx context.Context, message *sarama.ConsumerMessage) error// consumerImpl implementstype consumerImpl struct { topics []string consumerGroup sarama.ConsumerGroup handler MessageHandler retryConfig RetryConfig infoChannel chan string errorChannel chan error ready chan bool}// RetryConfig consumer's retry configtype RetryConfig struct { EnableRetry bool MaximumRetryTime int InitialDelayTime time.Duration MaximumDelayTime time.Duration}// NewKafkaConsumer create a new kafka consumerfunc NewKafkaConsumer(topics []string, brokers []string, consumerGroupName string, config *sarama.Config, handler MessageHandler, retryConfig RetryConfig) (Consumer, error) { consumer := &consumerImpl{ topics: topics, handler: handler, retryConfig: retryConfig, ready: make(chan bool), infoChannel: make(chan string, 1), errorChannel: make(chan error, 1), } consumerGroup, err := sarama.NewConsumerGroup(brokers, consumerGroupName, config) if err != nil { return nil, err } consumer.consumerGroup = consumerGroup return consumer, nil}// Start set up a new sarama consumer groupfunc (c *consumerImpl) Start(ctx context.Context) error { ctx, cancel := context.WithCancel(ctx) wg := &sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() if err := c.consumerGroup.Consume(ctx, c.topics, c); err != nil { logError(c.errorChannel, errors.New("consumer error")) } if ctx.Err() != nil { return } c.ready = make(chan bool) }() go func() { defer wg.Done() c.listenLog() }() // NOTE <-r.ready will block util close(c.ready) <-c.ready // wait till the consumer has been set up logInfo(c.infoChannel, fmt.Sprintf("sarama consumer up for topics %v up and running", c.topics)) sigterm := make(chan os.Signal, 1) signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM) select { case <-ctx.Done(): logInfo(c.infoChannel, fmt.Sprintf("terminating: context cancel")) case <-sigterm: logInfo(c.infoChannel, fmt.Sprintf("terminating: via signal")) } cancel() wg.Wait() if err := c.consumerGroup.Close(); err != nil { logInfo(c.infoChannel, fmt.Sprintf("close consumer group")) return err } return nil}// Setup is run at the beginning of a new session, before ConsumeClaimfunc (c *consumerImpl) Setup(session sarama.ConsumerGroupSession) error { close(c.ready) return nil}// Cleanup is run at the end of a session, once all ConsumeClaim goroutines have exitedfunc (c *consumerImpl) Cleanup(session sarama.ConsumerGroupSession) error { return nil}// ConsumeClaim must start a consumer loop of ConsumerGroupClaim's Messages()func (c *consumerImpl) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { for message := range claim.Messages() { if message == nil { continue } logInfo(c.infoChannel, fmt.Sprintf("processing message: %v", string(message.Value))) c.withBackoff(func() error { return c.handler(session.Context(), message) }, c.retryConfig) } return nil}func (c *consumerImpl) InfoChannel() <-chan string { return c.infoChannel}func (c *consumerImpl) ErrorChannel() <-chan error { return c.errorChannel}func (c *consumerImpl) listenLog() { for { select { case info := <-c.infoChannel: log.Println("[INFO] ", info) case err := <-c.errorChannel: log.Println("[ERROR]", err) } }}func (c *consumerImpl) withBackoff(f func() error, retryConfig RetryConfig) { if !retryConfig.EnableRetry { if err := c.runFunctionAndCapturePanic(f); err != nil { logError(c.errorChannel, errors.New("run function")) } return } delayTime := retryConfig.InitialDelayTime for i := 0; i < retryConfig.MaximumRetryTime+1; i++ { if err := c.runFunctionAndCapturePanic(f); err != nil { logError(c.errorChannel, errors.New("run function")) time.Sleep(delayTime) delayTime = delayTime << 1 if delayTime > retryConfig.MaximumDelayTime { delayTime = retryConfig.MaximumDelayTime } continue } return }}func (c *consumerImpl) runFunctionAndCapturePanic(f func() error) (err error) { defer func() { if r := recover(); r != nil { err = errors.New("no retry") } }() return f()}
Test
package kafkaimport ( "context" "log" "testing" "time" "github.com/Shopify/sarama")// @Author Chen Zikang// @Email zikang.chen@shopee.com// @Since 2022-05-08func StringMessageHandler(ctx context.Context, message *sarama.ConsumerMessage) error { log.Printf("Consume message: offset=%v, key=%v, value=%v\n", message.Offset, string(message.Key), string(message.Value)) return nil}func TestConsumer(t *testing.T) { var ( brokerList = []string{"127.0.0.1:9092"} topicList = []string{"hello-1"} consumerGroupName = "test" ) // config config := sarama.NewConfig() config.Version = sarama.V1_1_0_0 config.ClientID = "KHighness" config.Producer.RequiredAcks = sarama.WaitForAll config.Producer.Return.Successes = true config.Producer.Retry.Max = 10 config.Consumer.MaxProcessingTime = 1 * time.Hour // retry config retryConfig := RetryConfig{ EnableRetry: true, MaximumRetryTime: 10, InitialDelayTime: 1 * time.Second, MaximumDelayTime: 5 * time.Minute, } consumer, err := NewKafkaConsumer(topicList, brokerList, consumerGroupName, config, StringMessageHandler, retryConfig) if err != nil { log.Fatalln(err) } ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) defer cancel() log.Println("Consumer start successfully") err = consumer.Start(ctx) if err != nil { log.Fatalln(err) }}
package kafkaimport ( "context" "fmt" "log" "testing" "time" "github.com/Shopify/sarama")// @Author Chen Zikang// @Email zikang.chen@shopee.com// @Since 2022-05-08func TestProducer(t *testing.T) { var brokerList = []string{"127.0.0.1:9092"} // config config := sarama.NewConfig() config.Version = sarama.V1_1_0_0 config.ClientID = "KHighness" config.Producer.RequiredAcks = sarama.WaitForAll config.Producer.Return.Successes = true config.Producer.Retry.Max = 10 config.Consumer.MaxProcessingTime = 1 * time.Hour producer, err := NewKafkaProducer("hello-1", brokerList, config) if err != nil { log.Fatalln(err) } for i := 0; i < 5; i++ { key := fmt.Sprintf("%d", i) producer.SendMessage(context.Background(), &key, "KHighness") }}