我有一个kafka 0.10群集,其中有几个主题可以为他们制作消息。
当我订阅带有KafkaConsumer和新组ID的主题时,我没有返回任何记录,但是如果我订阅的主题是使用ConsumerRebalanceListener寻找同一组ID的开头,那么我将获得记录话题。
@Grab('org.apache.kafka:kafka-clients:0.10.0.0')
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.clients.consumer.ConsumerRecords
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.PartitionInfo
Properties props = new Properties()
props.with {
put("bootstrap.servers","***********:9091")
put("group.id","script-test-noseek")
put("enable.auto.commit","true")
put("key.deserializer","org.apache.kafka.common.serialization.StringDeserializer")
put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer")
put("session.timeout.ms",30000)
}
KafkaConsumer consumer = new KafkaConsumer(props)
def topicMap = [:]
consumer.listTopics().each { topic, partitioninfo ->
topicMap[topic] = 0
}
topicMap.each {topic, count ->
def stopTime = new Date().time + 30_000
def stop = false
println "Starting topic: $topic"
consumer.subscribe([topic])
//consumer.subscribe([topic], new CRListener(consumer:consumer))
while(!stop) {
ConsumerRecords<String, String> records = consumer.poll(5_000)
topicMap[topic] += records.size()
consumer.commitAsync()
if ( new Date().time > stopTime || records.size() == 0) {
stop = true
}
}
consumer.unsubscribe()
}
def total = 0
println "------------------- Results -----------------------"
topicMap.each { k,v ->
if ( v > 0 ) {
println "Topic: ${k.padRight(64,' ')} Records: ${v}"
}
total += v
}
println "==================================================="
println "Total: ${total}"
def dummy = "Process End"
class CRListener implements ConsumerRebalanceListener {
KafkaConsumer consumer
void onPartitionsAssigned(java.util.Collection partitions) {
consumer.seekToBeginning(partitions)
}
void onPartitionsRevoked(java.util.Collection partitions) {
consumer.commitSync()
}
}
代码是Groovy 2.4.x.我已经屏蔽了引导服务器。 如果我将消费者订阅行与侦听器取消注释,它就会按照我的预期执行。但是因为它没有结果。
假设我为每次运行更改了组ID,只是为了不在另一个执行中断的地方。
我无法看清我做错了什么。任何帮助将不胜感激。
答案 0 :(得分:3)
如果您使用新的使用者组ID并希望从头开始阅读整个主题,则需要在属性中指定参数“auto.offset.reset = earliest”。 (默认值为“最新”)
group.id
在消费者启动时会发生以下情况:
auto.offset.commit