Java简单实现Kafka生产者与消费者


    org.apache.kafka
    kafka-clients
    1.0.0

1、生产者示例代码

public class ProducerFastStart {

    public static final String brokerList = "node-01:9092";
    public static final String topic = "topic-demo";

    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("bootstrap.servers", brokerList);

        //配置生产者客户端参数并创建KafkaProducer实例
        KafkaProducer producer = new KafkaProducer<>(properties);
        //构建需要发送的消息
        ProducerRecord record = new ProducerRecord<>(topic, "hello, producer is coming!!");

        //发送消息
        producer.send(record);

        //关闭生产客户端
        producer.close();
    }
}

2、消费者示例代码

public class ConsumerFastStart {
    public static final String brokerList = "localhost:9092";
    public static final String topic = "topic-demo";
    public static final String groupId = "group.demo";
 
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("bootstrap.servers", brokerList);
 
        properties.put("group.id", groupId);
 
        //创建一个消费者客户端实例
        KafkaConsumer consumer = new KafkaConsumer<>(properties);
 
        //订阅主题
        consumer.subscribe(Collections.singletonList(topic));
 
        //循环消费消息
        while (true) {
            ConsumerRecords records = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord record : records) {
                System.out.println(record);
            }
        }
    }
}

 

你可能感兴趣的:(kafka,kafka)