Apache kafka 如何从一开始就使用Kafka Consumer API读取数据?
请告诉我,每次我运行消费者时,如何从一开始就使用Kafka消费者API阅读消息。同时使用高级消费者设置Apache kafka 如何从一开始就使用Kafka Consumer API读取数据?,apache-kafka,kafka-consumer-api,Apache Kafka,Kafka Consumer Api,请告诉我,每次我运行消费者时,如何从一开始就使用Kafka消费者API阅读消息。同时使用高级消费者设置props.put(“auto.offset.reset”,“minimable”)在创建消费者配置时 (二) 要重置消费者组,可以删除Zookeeper组id import kafka.utils.ZkUtils; ZkUtils.maybeDeletePath(<zkhost:zkport>, </consumers/group.id>);` 导入kafka.u
props.put(“auto.offset.reset”,“minimable”)代码>在创建消费者配置时
(二)
要重置消费者组,可以删除Zookeeper组id
import kafka.utils.ZkUtils;
ZkUtils.maybeDeletePath(<zkhost:zkport>, </consumers/group.id>);`
导入kafka.utils.ZkUtils;
ZkUtils.maybeDeletePath(,)`
这适用于0.9.x消费者。基本上,在创建消费者时,需要使用属性ConsumerConfig.group\u id\u CONFIG
为该消费者分配消费者组id。每次启动使用者执行类似以下操作时,随机生成使用者组idproperties.put(ConsumerConfig.group\u id\u CONFIG,UUID.randomuid().toString())代码>(properties是java.util.properties的一个实例,您将把它传递给构造函数新的KafkaConsumer(properties)
)
随机生成客户端意味着新的消费者组在kafka中没有任何关联的偏移量。所以在这之后我们要做的是为这个场景设置一个策略。正如auto.offset.reset
属性的文档所述:
如果Kafka中没有初始偏移量,或者服务器上不再存在当前偏移量(例如,因为该数据已被删除),该怎么办:
- 最早:自动将偏移重置为最早偏移
- 最新:自动将偏移重置为最新偏移
- 无:如果未找到以前的偏移量或使用者的组,则向使用者抛出异常
- 其他:向消费者抛出异常
因此,从上面列出的选项中,我们需要选择最早的
策略,以便新的消费群体每次都从头开始
您的java代码如下所示:
properties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString());
properties.put(ConsumerConfig.CLIENT_ID_CONFIG, "your_client_id");
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
consumer = new KafkaConsumer(properties);
现在您需要弄清楚的唯一一件事是,当有多个消费者属于同一消费者组但被分配时,如何生成一个随机id并在这些实例之间分配它,以便它们都属于同一消费者组
希望有帮助 如果您更具体地使用java consumer api org.apache.kafka.clients.consumer.consumer,可以尝试seek*方法
consumer.seekToBeginning(consumer.assignment())
这里是consumer.assignment()返回分配给给定使用者的所有分区,SeekToBegining将从给定分区集合的最早偏移量开始。执行此操作的一个选项是每次启动时都有一个唯一的组id,这意味着Kafka将从一开始就向您发送主题中的消息。为KafkaConsumer
设置属性时,请执行以下操作:
properties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString());
另一个选项是使用consumer.seektobegining(consumer.assignment())
,但除非Kafka首先通过让消费者调用poll方法从消费者那里获得心跳信号,否则这将不起作用。因此,调用poll()。这有点骇客,但从0.9版本开始,这似乎是最可靠的方法
// At this point, there is no heartbeat from consumer so seekToBeinning() wont work
// So call poll()
consumer.poll(0);
// Now there is heartbeat and consumer is "alive"
consumer.seekToBeginning(consumer.assignment());
// Now consume
ConsumerRecords<String, String> records = consumer.poll(0);
//此时,消费者没有心跳信号,因此seekToBeinning()无法工作
//所以调用poll()
消费者调查(0);
//现在有心跳,消费者“活着”
consumer.seektobegining(consumer.assignment());
//现在消费
ConsumerRecords记录=consumer.poll(0);
一种可能的解决方案是在订阅一个或多个主题时使用ConsumerBalanceListener的实现。当从使用者分配或移除新分区时,ConsumerBalanceListener包含回调方法。以下代码示例说明了这一点:
public class SkillsConsumer {
private String topic;
private KafkaConsumer<String, String> consumer;
private static final int POLL_TIMEOUT = 5000;
public SkillsConsumer(String topic) {
this.topic = topic;
Properties properties = ConsumerUtil.getConsumerProperties();
properties.put("group.id", "consumer-skills");
this.consumer = new KafkaConsumer<>(properties);
this.consumer.subscribe(Collections.singletonList(this.topic),
new PartitionOffsetAssignerListener(this.consumer));
}
}
public class PartitionOffsetAssignerListener implements ConsumerRebalanceListener {
private KafkaConsumer consumer;
public PartitionOffsetAssignerListener(KafkaConsumer kafkaConsumer) {
this.consumer = kafkaConsumer;
}
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
//reading all partitions from the beginning
for(TopicPartition partition : partitions)
consumer.seekToBeginning(partition);
}
公共类技能消费者{
私有字符串主题;
私人卡夫卡消费品;
私有静态最终整数轮询超时=5000;
公共技能消费者(字符串主题){
this.topic=主题;
Properties=consumerrutil.getConsumerProperties();
房产出售(“集团id”、“消费者技能”);
this.consumer=新卡夫卡消费者(财产);
this.consumer.subscribe(Collections.singletonList(this.topic)),
新的PartitionOffsetAssignerListener(this.consumer));
}
}
公共类PartitionOffsetAssignerListener实现ConsumerBalanceListener{
私人卡夫卡消费品;
公共分区OffsetAssignerListener(卡夫卡消费者卡夫卡消费者){
this.consumer=kafkaConsumer;
}
@凌驾
已撤销分区上的公共void(集合分区){
}
@凌驾
已签名的分区上的公共void(集合分区){
//从一开始就读取所有分区
for(主题分区:分区)
消费者。参见目标划分(分区);
}
}
现在,只要将分区分配给使用者,就会从一开始读取每个分区 所以对我来说,有效的方法是上述建议的结合。关键的变化是包括
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
并且每次都有一个随机生成的组ID。但这一点对我来说不起作用。出于某种原因,我第一次对消费者进行调查时,它从未得到任何记录。我必须破解它才能让它工作-
consumer.poll(0); // without this the below statement never got any records
final ConsumerRecords<Long, String> consumerRecords = consumer.poll(Duration.ofMillis(100));
consumer.poll(0);//没有这个,下面的陈述就没有任何记录
最终消费者记录消费者记录=消费者投票(持续时间为100百万);
我是卡夫卡的新手,不知道为什么会发生这种情况,但对于其他仍在努力实现这一点的人来说,希望这能有所帮助
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
如果您只是避免保存任何偏移,则消费者将始终在开始时重置。另一个选项是保持消费者代码简单,并使用命令行工具kafka消费者组
从外部控制偏移管理
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 \
--execute --reset-offsets \
--group myConsumerGroup \
--topic myTopic \
--to-earliest
--reset-offsets also has following scenarios to choose from (atleast one scenario must be selected):
--to-datetime <String: datetime> : Reset offsets to offsets from datetime. Format: 'YYYY-MM-DDTHH:mm:SS.sss'
--to-earliest : Reset offsets to earliest offset.
--to-latest : Reset offsets to latest offset.
--shift-by <Long: number-of-offsets> : Reset offsets shifting current offset by 'n', where 'n' can be positive or negative.
--from-file : Reset offsets to values defined in CSV file.
--to-current : Resets offsets to current offset.
--by-duration <String: duration> : Reset offsets to offset by duration from current timestamp. Format: 'PnDTnHnMnS'
--to-offset : Reset offsets to a specific offset.
// ... Assuming the props have been set properly.
// ... enable.auto.commit and auto.offset.reset as default
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList(topic));
consumer.poll(0); // without this, the assignment will be empty.
consumer.assignment().forEach(t -> {
System.out.printf("Set %s to offset 0%n", t.toString());
consumer.seek(t, 0);
});
while (true) {
// ... consumer polls messages as usual.
}