内容简介:SpringBoot Kafka 整合使用
假设你了解过 SpringBoot 和 Kafka。
1、SpringBoot
如果对 SpringBoot 不了解的话,建议去看看 DD 大佬 和 纯洁的微笑 的系列博客。
2、Kafka
Kafka 的话可以看看我前两天写的博客 :Kafka 安装及快速入门 学习的话自己开台虚拟机自己手动搭建环境吧,有条件的买服务器。
注意: 一定要亲自自己安装实践 ,接下来我们将这两个进行整合。
创建项目
项目整体架构:
使用 IDEA 创建 SpringBoot 项目,这个很简单了,这里不做过多的讲解。
1、pom 文件代码如下:
<?xml version="1.0"encoding="UTF-8"?>
<projectxmlns="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>com.zhisheng</groupId>
<artifactId>kafka-learning</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>kafka-learning</name>
<description>Demo project for Spring Boot + kafka</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
主要引入了 spring-kafka 、lombok 、 gson 依赖。
2、消息实体类 Message.java 如下:
@Data
public class Message{
private Long id; //id
private String msg; //消息
private Date sendTime; //时间戳
}
3、消息发送类 KafkaSender.java
@Component
@Slf4j
public class KafkaSender{
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
private Gson gson = new GsonBuilder().create();
//发送消息方法
public void send(){
Message message = new Message();
message.setId(System.currentTimeMillis());
message.setMsg(UUID.randomUUID().toString());
message.setSendTime(new Date());
log.info("+++++++++++++++++++++ message = {}", gson.toJson(message));
kafkaTemplate.send("zhisheng", gson.toJson(message));
}
}
就这样,发送消息代码就实现了。
这里关键的代码为 kafkaTemplate.send() 方法, zhisheng 是 Kafka 里的 topic ,这个 topic 在 Java 程序中是不需要提前在 Kafka 中设置的,因为它会在发送的时候自动创建你设置的 topic, gson.toJson(message) 是消息内容,这里暂时先说这么多了,不详解了,后面有机会继续把里面源码解读写篇博客出来(因为中途碰到坑,老子跟了几遍源码)。
4、消息接收类 KafkaReceiver.java
@Component
@Slf4j
public class KafkaReceiver{
@KafkaListener(topics = {"zhisheng"})
public void listen(ConsumerRecord<?, ?> record){
Optional<?> kafkaMessage = Optional.ofNullable(record.value());
if (kafkaMessage.isPresent()) {
Object message = kafkaMessage.get();
log.info("----------------- record =" + record);
log.info("------------------ message =" + message);
}
}
}
客户端 consumer 接收消息特别简单,直接用 @KafkaListener 注解即可,并在监听中设置监听的 topic , topics 是一个数组所以是可以绑定多个主题的,上面的代码中修改为 @KafkaListener(topics = {"zhisheng","tian"}) 就可以同时监听两个 topic 的消息了。需要注意的是:这里的 topic 需要和消息发送类 KafkaSender.java 中设置的 topic 一致。
5、启动类 KafkaApplication.java
@SpringBootApplication
public class KafkaApplication{
public static void main(String[] args){
ConfigurableApplicationContext context = SpringApplication.run(KafkaApplication.class, args);
KafkaSender sender = context.getBean(KafkaSender.class);
for (int i = 0; i < 3; i++) {
//调用消息发送类中的消息发送方法
sender.send();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
6、配置文件 application.properties
#============== kafka =================== # 指定kafka 代理地址,可以多个 spring.kafka.bootstrap-servers=192.168.153.135:9092 #=============== provider ======================= spring.kafka.producer.retries=0 # 每次批量发送消息的数量 spring.kafka.producer.batch-size=16384 spring.kafka.producer.buffer-memory=33554432 # 指定消息key和消息体的编解码方式 spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer #=============== consumer ======================= # 指定默认消费者group id spring.kafka.consumer.group-id=test-consumer-group spring.kafka.consumer.auto-offset-reset=earliest spring.kafka.consumer.enable-auto-commit=true spring.kafka.consumer.auto-commit-interval=100 # 指定消息key和消息体的编解码方式 spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.bootstrap-servers 后面设置你安装的 Kafka 的机器 IP 地址和端口号 9092。
如果你只是简单整合下,其他的几个默认就好了。
Kafka 设置
在你安装的 Kafka 目录文件下:
启动 zk
使用安装包中的脚本启动单节点 Zookeeper 实例:
bin/zookeeper-server-start.sh -daemon config/zookeeper.properties
启动 Kafka 服务
使用 kafka-server-start.sh 启动 kafka 服务:
bin/kafka-server-start.sh config/server.properties
启动成功后!
千万注意: 记得将你的虚拟机或者服务器关闭防火墙或者开启 Kafka 的端口 9092。
运行
出现这就代表整合成功了!
我们看下 Kafka 中的 topic 列表就
bin/kafka-topics.sh --list --zookeeper localhost:2181
就会发现刚才我们程序中的 zhisheng 已经自己创建了。
以上所述就是小编给大家介绍的《SpringBoot Kafka 整合使用》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- SpringBoot RabbitMQ 整合使用
- SpringBoot ActiveMQ 整合使用
- SpringBoot RabbitMQ 整合使用
- Redis和Lua初步整合使用
- redis与spring整合使用的步骤实例教程
- 框架—SpringBoot整合Mybatis使用Druid数据源
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Agile Web Application Development with Yii 1.1 and PHP5
Jeffrey Winesett / Packt Publishing / 2010-08-27
In order to understand the framework in the context of a real-world application, we need to build something that will more closely resemble the types of applications web developers actually have to bu......一起来看看 《Agile Web Application Development with Yii 1.1 and PHP5》 这本书的介绍吧!
XML、JSON 在线转换
在线XML、JSON转换工具
XML 在线格式化
在线 XML 格式化压缩工具