springboot 集成 kafka
环境准备
安装kafka
brew install kafka
安装zookeeper
这里不需要安装了,因为kafka依赖zookeeper,所以安装kafka,会自动安装zookeeper
了解安装所在目录
- kafka : /usr/local/Cellar/kafka/2.4.1
- zookeeper : /usr/local/Cellar/kafka/2.4.1
终端验证kafka功能
启动
- 启动zookeeper
进入kafka安装目录( /usr/local/Cellar/kafka/2.4.1)
./bin/zookeeper-server-start /usr/local/etc/kafka/zookeeper.properties
- 启动kafka
进入kafka安装目录( /usr/local/Cellar/kafka/2.4.1)
./bin/kafka-server-start /usr/local/etc/kafka/server.properties
- 创建topic : abc123
./bin/kafka-topics --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic abc123
结果 :
Created topic abc123.
- 查看topic
./bin/kafka-topics --list --zookeeper localhost:2181
结果 :
__consumer_offsets
abc123
消息发送与消费
Kafka提供了一个命令行客户端,它将从文件或标准输入接收输入,并将其作为消息发送到Kafka集群。默认情况下,每行都将作为单独的消息发送。
运行生产者,然后在控制台中键入一些消息发送到服务器。
./bin/kafka-console-producer --broker-list localhost:9092 --topic abc123
Kafka还有一个命令行消费者,将消息转储到标准输出。
./bin/kafka-console-consumer --bootstrap-server localhost:9092 --topic abc123 --from-beginning
如图,上面的是生产者,下面的是消费者,依次发送hehe,haha,gan….,消费者依次会收到对应的消息。
springboot集成kafka
pom依赖
<!--kafka-->
<!-- https://mvnrepository.com/artifact/org.springframework.kafka/spring-kafka -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.4.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
application.properties 配置
#kafka
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=myGroup
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
实体定义
package com.example.demo.kafka;
import lombok.Data;
import java.util.Date;
@Data
public class Message {
private Long id;
private String msg;
private Date sendTime;
}
发送消息
package com.example.demo.kafka;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka