Kafka入门demo1

119 阅读1分钟

依赖引入

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>1.0.1</version>
</dependency>

创建生产者

public class ProducerFastStart {
    public final static String BROKER_LIST = "101.43.89.168: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",BROKER_LIST);
        // 配置生产者客户端参数并创建KafkaProducer实例
        KafkaProducer<String,String> producer =
                new KafkaProducer<String, String>(properties);
        // 构建所需要发送的消息
        ProducerRecord<String,String> record =
                new ProducerRecord<>(TOPIC,"hello,Kafka");
        // 发送消息
        try{
            System.out.println("sending message...");
            producer.send(record);
            System.out.println("sending message done...");
        }catch (Exception e){
            e.printStackTrace();
        }
        // 关闭生产者客户端
        producer.close();

    }
}

创建消费者

public class ConsumerFastStart {
    public final static String BROKER_LIST = "101.43.89.168:9092";
    public static final String TOPIC = "topic-demo";
    public static final String GROUP_ID = "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",BROKER_LIST);

        // 设置消费组的名称
        properties.put("group.id",GROUP_ID);
        // 构建一个消费者客户端实例
        KafkaConsumer<String,String> consumer =
                new KafkaConsumer<String, String>(properties);
        consumer.subscribe(Collections.singletonList(TOPIC));

        // 循环消费消息
        while (true){
            ConsumerRecords<String, String> records = consumer.poll(1000);
            for (ConsumerRecord<String,String> record:records){
                System.out.println(record.value());
            }
        }
    }
}

发送消息

  • 启动zookeeper bin/zookeeper-server-start.sh -daemon config/zookeeper.properties
  • 启动Kafka bin/kafka-server-start.sh config/server.properties
  • 启动ConsumerFastStart、ProducerFastStart

image.png

image.png

image.png

  • 查看消息消费情况 bin/kafka-consumer-groups.sh --bootstrap-server 101.43.89.168:9092 --group group.demo --describe

image.png