簡體   English   中英

如何使用 Sarama 從多個 goroutine 中的 Kafka 主題中消費?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM