golang如何连接kafka
时间: 2023-10-06 18:08:22 浏览: 66
可以使用第三方库sarama来连接kafka。以下是示例代码:
```
package main
import (
"fmt"
"github.com/Shopify/sarama"
)
func main() {
// 设置kafka配置
config := sarama.NewConfig()
config.Consumer.Return.Errors = true
// 连接broker
broker := "localhost:9092"
client, err := sarama.NewClient([]string{broker}, config)
if err != nil {
panic(err)
}
defer client.Close()
// 创建kafka消费者
consumer, err := sarama.NewConsumerFromClient(client)
if err != nil {
panic(err)
}
defer consumer.Close()
// 指定要消费的topic
topic := "test-topic"
// 创建kafka消费者的分区列表
partitionList, err := consumer.Partitions(topic)
if err != nil {
panic(err)
}
// 遍历分区列表并消费
for _, partition := range partitionList {
pc, err := consumer.ConsumePartition(topic, partition, sarama.OffsetNewest)
if err != nil {
panic(err)
}
defer pc.AsyncClose()
go func(pc sarama.PartitionConsumer) {
for msg := range pc.Messages() {
fmt.Printf("Partition:%d Offset:%d Key:%s Value:%s\n", msg.Partition, msg.Offset, string(msg.Key), string(msg.Value))
}
}(pc)
}
// 持续消费
select {}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)