![](/img/trans.png)
[英]How to consume from latest offset using Sarama Go Kafka Consumer
[英]How to consume from Kafka topic in multiple goroutines, using Sarama?
我使用https://github.com/Shopify/sarama与 Kafka 进行交互。 我有一个主题,例如100 个分区。 我有应用程序,它部署在1 台主机上。 所以,我想在多个 goroutine 中使用这个主题。
我看到这个例子 - https://github.com/Shopify/sarama/blob/master/examples/consumergroup/main.go ,在其中我们可以看到,如何在特定的消费者组中创建消费者。
所以,我的问题是,我应该创建多个这样的消费者,还是在Sarama
有一些设置,我可以在其中设置所需数量的消费者 goroutine。
PS 我看到这个问题 - https://github.com/Shopify/sarama/issues/140 - 但没有答案,如何创建MultiConsumer
。
此示例显示了一个完全工作的控制台应用程序,它可以为主题中的所有分区使用,为每个分区创建一个 goroutine:
https://github.com/Shopify/sarama/blob/master/tools/kafka-console-consumer/kafka-console-consumer.go
它链接在您在问题中发布的线程的末尾。
它基本上创建了一个消费者:
c, err := sarama.NewConsumer(strings.Split(*brokerList, ","), config)
然后获取所需主题的所有分区:
func getPartitions(c sarama.Consumer) ([]int32, error) {
if *partitions == "all" {
return c.Partitions(*topic)
}
...
然后为每个分区创建一个 PartitionConsumer 并在不同的 goroutine 中从每个分区中消费:
for _, partition := range partitionList {
pc, err := c.ConsumePartition(*topic, partition, initialOffset)
....
wg.Add(1)
go func(pc sarama.PartitionConsumer) {
defer wg.Done()
for message := range pc.Messages() {
messages <- message
}
}(pc)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.