sarama发送消息到kafka

依赖第三方包

"github.com/Shopify/sarama"

1.初始化异步生产者对象

package kafka

import (
	"fmt"

	"github.com/Shopify/sarama"
)

var (
	producer sarama.AsyncProducer
)

func Init(address []string) (err error) {
	producer, err = sarama.NewAsyncProducer(address, nil)
	if err != nil {
		fmt.Printf("init sarama failed,%#v\n", err)
		return
	}
	return
}

2.异步发送消息

func SendMessage(topic string, msg string) {
	// 使用producer对象的Input方法返回一个chan,往这个管道里塞数据就好了
	producer.Input() <- &sarama.ProducerMessage{Topic: topic, Key: nil, Value: sarama.StringEncoder(msg)}
}
posted @ 2022-05-25 22:14  SpecialSpeculator  阅读(156)  评论(0编辑  收藏  举报