在ConsumerConfig这个类中定义了这个属性的默认值,如下图
也就是默认值为latest,它的含义是:如果没有客户端提交过offset的话,当新的客户端消费时,把最新的offset设置为当前消费的offset.
默认是自动提交位移的,每5秒进行一次提交。可以通过参数配置手动提交。
手动提交offset的示例
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import java.time.Duration;
import java.time.temporal.TemporalUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
/*
设置手动提交offset
*/
public class KafkaTest08 {
private static Properties getProperties(){
Properties properties=new Properties();
properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"xx.xx.xx.xx:9092");
properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG,"testGroup8");
//设置手动提交位移
properties.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");
return properties;
}
public static void main(String[] args) {
KafkaConsumer<String,String> myConsumer=new KafkaConsumer<String, String>(getProperties());
myConsumer.subscribe(Arrays.asList("student"));
int i=0;
while(true){
ConsumerRecords<String,String> consumerRecords=myConsumer.poll(Duration.ofMillis(5000));
for(ConsumerRecord record: consumerRecords){
System.out.println(record.value());
System.out.println("record offset is: "+record.offset());
}
myConsumer.commitSync();
if(i==0){
//myConsumer.commitSync();
i ++;
}
else {
i ++;
}
}
}
}
版权归原作者 amadeus_liu2 所有, 如有侵权,请联系我们删除。