Kafka-Java三:Spring配置Kafka消费者消费消息

package com.demo.lxb.kafka;

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.common.serialization.StringSerializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;

/**
 * @Description: kafka消费者消费消息,消费者端默认是同步提交offset策略
 * @Author: lvxiaobu
 * @Date: 2023-10-24 16:26
 **/
public class MyConsumer {

    private  final static String CONSUMER_GROUP_NAME = "GROUP1"; // 消费者组
    private  final static String TOPIC_NAME = "topic0921";       // 主题

    public static void main(String[] args) {
        Properties props = new Properties();

        // 一、设置参数
        // 配置kafka地址
//        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
//                "192.168.151.28:9092"); // 单机配置
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
                "192.168.154.128:9092,192.168.154.128:9093,192.168.154.128:9094"); // 集群配置
        // 配置消息 键值的序列化规则
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());
        // 配置消费者组
        props.put(ConsumerConfig.GROUP_ID_CONFIG,CONSUMER_GROUP_NAME);

        // 二、创建消费者
        KafkaConsumer consumer = new KafkaConsumer(props);
        // 三、消费者订阅主题
        consumer.subscribe(Collections.singletonList(TOPIC_NAME));

        // 四、开始消费
        while (true){
            // 消费者以poll的形式,从kafka集群中拉取消息
            ConsumerRecords records = consumer.poll(Duration.ofMillis(1000));
            
            for (ConsumerRecord record : records) {
                System.out.println("接收到的消息: 分区: " + record.partition() + ", offset: " + record.offset()
                + ", key值: " + record.key() + " , value值: "+record.value());
            }
        }
    }
}

你可能感兴趣的:(SPRING,JAVA,消息队列-kafka,java,kafka,spring)