kafka 生产者,消费者代码 - 基于Java代码

一、生产者

1.pom文件添加

       
            org.apache.kafka
            kafka-clients
            2.0.1
        

2.生产数据demo

package test;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

public class KafkaClient {


    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092");
        props.put("acks", "all");
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        String event="某json数据";
        Producer producer = new KafkaProducer<>(props);
        for (int i = 0; i < 100; i++) {
            producer.send(new ProducerRecord("你的topic,没有的话,会自动生成", "1", event));
        }

        producer.close();
    }

}

3.shell 控制台查看kafka消费数据

./bin/kafka-console-consumer.sh --bootstrap-server test:9092 --topic "topic名称"

注:可以查看你所有的topic

    bin/kafka-topics.sh --list --zookeeper localhost:2181

持续记录

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