1 kafka集群操作
#1、创建topic
#创建一个名字为test的主题, 有三个分区,有两个副本
#node01执行以下命令来创建topic
cd /opt/module/kafka_2.11-1.0.0
bin/kafka-topics.sh --create --partitions 3 --replication-factor 2 --topic test --zookeeper hadoop102:2181, hadoop103:2181, hadoop104:2181
#2、查看主题命令
#查看kafka当中存在的主题
node01使用以下命令来查看kafka当中存在的topic主题
cd /opt/module/kafka_2.11-1.0.0
bin/kafka-topics.sh --list --zookeeper hadoop102:2181, hadoop103:2181, hadoop104:2181
#3、生产者生产数据
#模拟生产者来生产数据
#node01服务器执行以下命令来模拟生产者进行生产数据
cd /opt/module/kafka_2.11-1.0.0
bin/kafka-console-producer.sh --broker-list hadoop102:9092, hadoop103:9092, hadoop104:9092 --topic test
#4、消费者消费数据
#node02服务器执行以下命令来模拟消费者进行消费数据
cd /opt/module/kafka_2.11-1.0.0
bin/ kafka-console-consumer.sh --from-beginning --topic test --zookeeper node01:2181,node02:2181,node03:2181
2 kafka的JavaAPI操作
- 需要添加的依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients -->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
2.1 生产者代码
/**
* 订单的生产者代码,
*/
public class OrderProducer {
public static void main(String[] args) throws InterruptedException {
/* 1、连接集群,通过配置文件的方式
* 2、发送数据-topic:order,value
*/
Properties props = new Properties();
props.put("bootstrap.servers", "hadoop102:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
KafkaProducer<String, String> kafkaProducer = new KafkaProducer<Stri