从分区的开始进行消费,因为kafka会定期清理历史数据,所以分区开始的位移不一定为0。seekToBeginning只是从目前保留的数据中最小的offset进行消费
package com.cisdi.dsp.modules.metaAnalysis.rest.kafka2023;
import org.apache.kafka.clients.consumer.*;
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;
/*
从分区开头进行消费; seekToBeginning)
*/
public class KafkaTest14 {
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,"testGroup12");
//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"));
Set<TopicPartition> topicPartitionSet = new HashSet<>();
while(topicPartitionSet.size() == 0){
ConsumerRecords<String,String> consumerRecords=myConsumer.poll(Duration.ofMillis(5000));
topicPartitionSet = myConsumer.assignment();
}
myConsumer.seekToBeginning(topicPartitionSet);
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());
}
}
}
}
本文转载自: https://blog.csdn.net/amadeus_liu2/article/details/132490005
版权归原作者 amadeus_liu2 所有, 如有侵权,请联系我们删除。
版权归原作者 amadeus_liu2 所有, 如有侵权,请联系我们删除。