Kafka Consumer hanging at .hasNext in java

2020-03-01 18:02发布

I have a simple Kafka Consumer in java with the following code

    public void run() {
        ConsumerIterator<byte[], byte[]> it = m_stream.iterator();
        while (it.hasNext()&& !done){
            try {
                System.out.println("Parsing data");
                byte[] data = it.next().message();
                System.out.println("Found data: "+data);
                values.add(data); // array list
            } catch (InvalidProtocolBufferException e) {
                e.printStackTrace();
            }
        }
        done = true;
    }

When a message is posted, the data is read successfully, however when it goes back to checking it.hasNext(), it stays pending and never comes back.

What could be stalling this?

m_stream is a KafkaStream obtained as follows:

Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
topicCountMap.put(topic, new Integer(a_numThreads));
Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap);
List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(topic);
executor = Executors.newFixedThreadPool(a_numThreads);
for (final KafkaStream stream : streams) {
   // m_stream is one of these streams
}

2条回答
我想做一个坏孩纸
2楼-- · 2020-03-01 18:53

The solution was to add the property

"consumer.timeout.ms"

Now when the timeout is reached a ConsumerTimeoutException is thrown

查看更多
▲ chillily
3楼-- · 2020-03-01 18:54

The method hasNext() is blocking.

you can change the timeout of the blocking in the propertyconsumer.timeout.ms

Note that it will throw a TimeoutException when the timeout will expire.

Would read these docs about the consumers: https://cwiki.apache.org/confluence/display/KAFKA/Consumer+Group+Example https://cwiki.apache.org/confluence/display/KAFKA/0.8.0+SimpleConsumer+Example

查看更多
登录 后发表回答