我正在尝试使用最低级别的Consumer Java API来手动管理偏移,使用最新的kafka_2.10-0.8.2.1 . 要验证我从Kafka提交/读取的偏移量是否正确,我使用kafka.tools.ConsumerOffsetChecker工具 .
以下是我的主题/使用者组的输出示例:
./bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --group elastic_search_group --zookeeper localhost:2181 --topic my_log_topic
Group Topic Pid Offset logSize Lag Owner
elastic_search_group my_log_topic 0 5 29 24 none
以下是我对结果的解释:
Offset = 5 - >这是我'elastic_search_group'消费者的当前偏移量
logSize = 29 - >这是最新偏移量 - 将来到此主题/分区的下一条消息的偏移量
滞后= 24 - > 29-5 - 我的'elastic_search_group'消费者尚未处理多少消息
Pid - 分区ID
Q1:这是对的吗?
现在,我想从我的Java消费者那里获得相同的信息 . 在这里,我发现我必须使用两种不同的API:
kafka.javaapi . OffsetRequest 获得最早和最新的抵消,但kafka.javaapi . OffsetFetchRequest 获取当前偏移量 .
要获得最早(或最新)的偏移我做:
TopicAndPartition topicAndPartition = new TopicAndPartition(myTopic, myPartition);
Map requestInfo = new HashMap();
requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(OffsetRequest.EarliestTime(), 1));
// OR for Latest: requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(OffsetRequest.LatestTime(), 1));
kafka.javaapi.OffsetRequest request = new kafka.javaapi.OffsetRequest(
requestInfo, kafka.api.OffsetRequest.CurrentVersion(), clientName);
OffsetResponse response = simpleConsumer.getOffsetsBefore(request);
long[] offsets = response.offsets(topic, partition);
long myEarliestOffset = offsets[0];
// OR for Latest: long myLatestOffset = offsets[0];
要获得当前的偏移量,我必须使用完全不同的API:
short versionID = 0;
int correlationId = 0;
List topicPartitionList = new ArrayList();
TopicAndPartition myTopicAndPartition = new TopicAndPartition(myTopic, myPartition);
topicPartitionList.add(myTopicAndPartition);
OffsetFetchRequest offsetFetchReq = new OffsetFetchRequest(
kafkaGroupId, topicPartitionList, versionID, correlationId, kafkaGroupId);
OffsetFetchResponse offsetFetchResponse = simpleConsumer.fetchOffsets(offsetFetchReq);
long currentOffset = offsetFetchResponse.offsets().get(myTopicAndPartition).offset();
Q2:这是对的吗?为什么有两种不同的API来获取非常相似的信息?
问题3:我在这里使用哪个versionId和correlationId有关系吗?虽然versionId对于0.8.2.1之前的kafka应该是0,对于0.8.2.1及更高版本应该是1 - 但是看起来它也适用于0而0.8.2.1 - 见下文?
因此,对于上述主题的示例状态,以及ConsumerOffsetChecker的上述输出,以下是我从Java代码中获得的内容:
currentOffset=5; earliestOffset=29; latestOffset=29
'currentOffset'似乎没问题,'latestOffset'也是正确的,但'earliestOffset'?我希望它至少是'5'?
问题4:如果最早的偏移量高于currentOffset,怎么可能发生?我唯一的怀疑是,由于保留政策,可能会清除主题中的消息....这可能发生的任何其他情况?