簡體   English   中英

Kafka 消費者從多個主題中讀取

[英]Kafka Consumer to read from multiple topics

我對卡夫卡很陌生。 我正在創建兩個主題並從兩個生產者發布這兩個主題。 我有一個消費者,它使用來自這兩個主題的消息。 這是因為我想根據優先級進行處理。

我從這兩個主題中都得到了一個流,但是一旦我開始迭代任何流的ConsumerItreator ,它就會阻塞在那里。 正如文檔中所寫,它將被阻止,直到收到新消息。

有沒有人知道如何從單個 Kafka 消費者的兩個主題和兩個流中讀取數據?

    Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
                topicCountMap.put(KafkaConstants.HIGH_TEST_TOPIC, new Integer(1));
                topicCountMap.put(KafkaConstants.LOW_TEST_TOPIC, new Integer(1));
                Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumerConnector.createMessageStreams(topicCountMap);
                KafkaStream<byte[], byte[]> highPriorityStream = consumerMap.get(KafkaConstants.HIGH_TEST_TOPIC).get(0);
                ConsumerIterator<byte[], byte[]> highPrioerityIterator = highPriorityStream.iterator();

                while (highPriorityStream.nonEmpty() && highPrioerityIterator.hasNext())
                {
                    byte[] bytes = highPrioerityIterator.next().message();
                    Object obj = null;
                    CLoudDataObject thunderDataObject = null;
                    try
                    {

                        obj = SerializationUtils.deserialize(bytes);
                        if (obj instanceof CLoudDataObject)
                        {
                            thunderDataObject = (CLoudDataObject) obj;
                            System.out.println(thunderDataObject);
                            // TODO Got the Thunder object here, now write code to send it to Thunder service.
                        }

                    }
                    catch (Exception e)
                    {
                    }
                }

如果您不想在高優先級消息之前處理低優先級消息,那么如何設置 consumer.timeout.ms 屬性並捕獲 ConsumerTimeoutException 以檢測高優先級流是否到達最后一條可用消息? 默認情況下,它設置為 -1 以阻止直到新消息到達。 ( http://kafka.apache.org/07/configuration.html )

下面解釋了一種同時處理具有不同優先級的多個流的方法。

Kafka 需要多線程編程。 在您的情況下,兩個主題的流需要由流的線程處理。 因為每個線程會獨立運行來處理消息,一個阻塞流(線程)不會影響其他流。

Java 的 ThreadPool 實現可以幫助創建多線程應用程序。 您可以在此處找到示例實現:

https://cwiki.apache.org/confluence/display/KAFKA/Consumer+Group+Example

關於執行的優先級,您可以調用 Thread.currentThread.setPriority 方法根據線程服務的 Kafka 主題來獲得適當的線程優先級。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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