卡夫卡消费者民意调查最新消息

时间:2018-05-17 10:03:00

标签: c++ apache-kafka

我正在使用CppKafka来编程Kafka消费者。我希望当我的消费者开始时,它只会轮询新到达的消息(即消息在消费者开始时间之后到达),而不是消费者偏移消息。

// Construct the configuration
Configuration config = {
    { "metadata.broker.list", "127.0.0.1:9092" },
    { "group.id", "1" },
    // Disable auto commit
    { "enable.auto.commit", false },
    // Set offest to latest to receive latest message when consumer start working
    { "auto.offset.reset", "latest" },
};

// Create the consumer
Consumer consumer(config);

consumer.set_assignment_callback([](TopicPartitionList& partitions) {
    cout << "Got assigned: " << partitions << endl;
});

// Print the revoked partitions on revocation
consumer.set_revocation_callback([](const TopicPartitionList& partitions) {
    cout << "Got revoked: " << partitions << endl;
});


string topic_name = "test_topic";
// Subscribe to the topic
consumer.subscribe({ topic_name });

据我所知,设置为auto.offset.reset的配置latest仅在消费者开始读取指定分区时没有提交偏移时才有效。所以我在这里猜测我应该在没有提交的情况下调用consumer.poll(),但感觉不对,我担心我会在路上打破一些东西。谁能告诉我正确的方法来实现我的要求?

2 个答案:

答案 0 :(得分:1)

如果“enable.auto.commit”设置为false并且您没有在代码中提交偏移量,则每次您的消费者启动它时,如果auto.offset.reset = earliest,则从主题中的第一条消息开始消息消耗

auto.offset.reset的默认值是“latest”,这意味着缺少有效的偏移量,消费者将从最新的记录开始读取(消费者开始运行后写的记录)。

根据您的上述问题,看起来auto.offset.reset = latest应该可以解决您的问题。

但是如果您需要基于实时的偏移量,则需要在消费者中应用时间过滤器。这意味着从消息有效负载中的某个自定义字段或消息的元属性(ConsumerRecord.timestamp())获取主题比较偏移时间的消息,并相应地进行进一步处理。

另请参阅此答案Retrieve Timestamp based data from Kafka

答案 1 :(得分:1)

使用seekToEnd(Collection partitions) 方法。 寻找每个给定分区的最后一个偏移量。该函数进行惰性求值,仅在调用 poll(long) 时查找所有分区中的最终偏移量。如果未提供分区,则查找所有当前分配的分区的最终偏移量。

相关问题