自动提交offset
每次按照offset设置的时间提交offset
自动提交offset的相关参数:
kafka自动提交是为了方便我们更加关注业务。
**enable.auto.commit:**是否开启自动提交offset功能。
auto.commit.interval.ms:自动提交offset的时间间
隔。
以下为自动提交的offset代码:
offset设置成latest,offset由异步的方式提交offset,每次从最新的方式offset消费
package com.ln.kafka.custom;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;
/**
* @ProjectName: kafka
* @Package: com.ln.kafka.custom
* @Name:AutoSubmitOffset
* @Author:linianest
* @CreateTime:2021/1/8 9:31
* @version:1.0
* @Description TODO: 消费者自动提交offset,默认是从最新的offset消费
*/
public class AutoSubmitOffset {
public static void main(String[] args) {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop101:9092");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.GROUP_ID_CONFIG, "1234");
// todo 自动提交offset,默认值为true,设置成false,就得手动提交
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
// todo 默认自动提交offset的时间是5秒,如果想加快,需要修改参数
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 1000);
// 创建对象
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
// 订阅的消费者主题
consumer.subscribe(Arrays.asList("first"));
while (true) {
// 拉取数据
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord record : records) {
System.out.printf("topic=%d,key=%s,value=%s%n", record.topic(), record.offset(), record.value());
}
}
}
}