kafka复习:(19): ConsumerRebalanceListener的用法

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;
/*
消费指定的时间戳之后的消息
 */

public class KafkaTest16 {

    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 myConsumer=new KafkaConsumer(getProperties());
        Map offsetMap = new HashMap<>();
        myConsumer.subscribe(Arrays.asList("student"), new ConsumerRebalanceListener() {
            @Override
            public void onPartitionsRevoked(Collection partitions) {
                myConsumer.commitSync(offsetMap);
                offsetMap.clear();
            }

            @Override
            public void onPartitionsAssigned(Collection partitions) {

            }
        });




        while(true){
            ConsumerRecords consumerRecords = myConsumer.poll(Duration.ofMillis(5000));
            for(ConsumerRecord record: consumerRecords){
                System.out.println(record.value());
                System.out.println(record.offset());
                offsetMap.put(new TopicPartition(record.topic(), record.partition()),
                        new OffsetAndMetadata(record.offset() +1 ));
            }
            myConsumer.commitAsync(offsetMap, null);

        }

    }
}

你可能感兴趣的:(kafka,kafka,linq,分布式)