六、Kafka consumer及ConsumerRebalanceListener实现

1. comsumer代码示例

public class ConsumerMessage {
     

    private static final String TOPIC_NAME = "topic-07";

    public static void main(String[] args) {
     
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", "192.168.111.129:9092,192.168.111.129:9093,192.168.111.129:9094");
        // 指定groupId
        props.setProperty("group.id", "ConsumerGroup2");
        /* 是否自动确认offset */
        props.setProperty("enable.auto.commit", "true");
        /* 自动确认offset的时间间隔 */
        props.setProperty("auto.commit.interval.ms", "1000");
        // earliest 最早的偏移量
        // latest   最后提交的偏移量
        // none     未找到消费者组的之前偏移量,则向消费者抛出e异常
        // props.put("auto.offset.reset", "earliest");
        props.put("session.timeout.ms", "30000");

        // 序列化类
        props.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Arrays.asList(TOPIC_NAME));

        try {
     
            for (; ; ) {
     
                // poll一次会返回一批数据
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
                for (ConsumerRecord<String, String> record : records) {
     
                    System.out.printf("消费消息:topic=%s, partition=%d, offset=%d, key=%s, value=%s\n",
                            record.topic(), record.partition(), record.offset(), record.key(), record.value());
                }
            }
        } finally {
     
            consumer.close();
        }
    }
}

2. 客户端负载均衡

public class RebalanceListener implements ConsumerRebalanceListener {
     
    /**
     * 伪代码,这里记录的是当前的偏移量
     */
    static Map<TopicPartition, OffsetAndMetadata> currentOffsets = new HashMap<>();
    private KafkaConsumer<String, String> consumer;
    /**
     * 初始化方法,传入consumer对象,否则无法调用外部的consumer对象,必须传入
     */
    public RebalanceListener(KafkaConsumer<String, String> consumer) {
     
        this.consumer = consumer;
    }
    /**
     * 该方法会在再均衡开始之前和消费者停止读取之后被调用。
     * 如果在这个方法中提交偏移量,则下一个消费者就可以获得读取的偏移量。
     */
    @Override
    public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
     
        System.out.println("分区再均衡,提交当前偏移量:" + currentOffsets);
        consumer.commitSync(currentOffsets);
    }
    /**
     * 该方法会在再均衡之后和消费者读取之前被调用
     */
    @Override
    public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
     
        long committedOffset = -1;
        for (TopicPartition topicPartition : partitions) {
     
            // 获取该分区已经提交的偏移量
            committedOffset = consumer.committed(topicPartition).offset();
            System.out.println("重新分配分区,提交的偏移量:" + committedOffset);
            // 重置偏移量到上一次提交的偏移量的下一个位置处开始消费
            consumer.seek(topicPartition, committedOffset + 1);
        }
    }
}

你可能感兴趣的:(Kafka)