1. Java代码编写Kafka的生产者---旧版本的生产者代码--不建议使用
1. 开启进程
[node123]systemctl stop firewalld
[node123]zkServer.sh start
[node123]kafka-server-start.sh /opt/app/kafka-0.11.0.0/config/server.properties &
[node1]kafka-console-consumer.sh --zookeeper node1:2181 --topic demo
2. java导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>kafkacode</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>0.11.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.12</artifactId>
<version>0.11.0.0</version>
</dependency>
</dependencies>
</project>
3. java代码
package old_out;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* Java代码编写Kafka的生产者---旧版本的生产者代码--不建议使用
*/
public class OldProducerOut {
public static void main(String[] args) {
// 定义生产者连接Kafka集群必备参数
Properties properties = new Properties();
properties.put("metadata.broker.list", "192.168.200.111:9092");
properties.put("request.required.acks", "1");
properties.put("serializer.class", "kafka.serializer.StringEncoder");
// 创建一个生产者
Producer producer = new Producer(new ProducerConfig(properties));
// 创建KeyedMessage对象---封装主题和数据
List<KeyedMessage> list = new ArrayList<KeyedMessage>();
for (int i = 0; i < 100; i++) {
KeyedMessage message = new KeyedMessage("demo", "java api" + i);
list.add(message);
}
producer.send(list);
}
}
4. 效果图
本文来自博客园,作者:jsqup,转载请注明原文链接:https://www.cnblogs.com/jsqup/p/16665678.html