一. 安装 Zookeeper
在此之前先安装Zookeeper之后就可以安装Kafka了,没有安装请 [点击此处跳转到相关文章]
问题:为什么搭建Kafka需要zookeeper?
kafka 很多说不需要安装zk的是因为他们都使用了kafka自带的zk 至于kafka为什么使用zk,你首先要知道zk的作用, 作为去中心化的集群模式。 需要要消费者知道现在那些生产者(对于消费者而言,kafka就是生产者)是可用的。 如果没了zk消费者如何知道呢?如果每次消费者在消费之前都去尝试连接生产者测试下是否连接成功,效率呢? 所以kafka需要zk,在kafka的设计中就依赖了zk了。
二.安装Kafka
参考安装地址:kafka安装教程
三.使用教程
Zookeeper启动命令(不要关闭):打开apache-zookeeper-3.7.1-bin\bin\zkServer.cmd
打开apache-zookeeper-3.7.1-bin\bin\zkCli.cmd
kafka启动命令(不要关闭):.\bin\windows\kafka-server-start.bat .\config\server.properties
使用的时候出现了个报错:
Topic(s) [test] is/are not present and missingTopicsFatal is true
查询发现是我kafka自己关闭了
重新开启后就可以使用了
四.使用实例
maven依赖
<!-- kafkfa -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
</dependency>
yml文件
spring:
application:
name: kafka-demo
kafka:
bootstrap-servers: 需要调用的kafka地址:端口号(默认9092)
producer:
retries: 10
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
consumer:
group-id: ${spring.application.name}-test
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
生产者:(按理说需要记录到数据库中,那就在封装一层kafka,进行存储每次执行状态)
kafkaTemplate.send("itcast-topic","测试发送消息");
消费者:(执行完成进行状态修改,反馈查看)
@KafkaListener(topics = "itcast-topic")
public void onMessage(String message){
if(!StringUtils.isEmpty(message)){
System.out.println("接收到的消息:"+message);
}
过程中会有一部分接收延迟