在上一篇文章中介绍了怎么在mac系统上搭建kafka,既然搭建成功了,肯定要集成到项目中使用啊,但是怎么集成呢,这里把我本人集成的代码以及怎么一步步集成的放上来,源码也会在本文的后面放出,下面来跟我一起看一下springboot怎么集成kafka的吧
基础环境
springboot version:springboot2.1.4.RELEASE
kafka version :2.2.0
- 集成之前先放上一张官网的kafka与Spring版本对应的关系表,后续如遇到消息不能正常发送接收就请排查一下是不是版本问题
地址链接[https://spring.io/projects/spring-kafka] - SQL
## 创建数据库表
# sql 生产消息一致表
CREATE TABLE `xy_kafka_in_msg` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`fw_bh` bigint(20) NOT NULL COMMENT '档案号',
`gmt_create` datetime NOT NULL COMMENT '创建时间',
`gmt_update` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `fwbh` (`fw_bh`) USING BTREE COMMENT '服务唯一标示'
) ENGINE=InnoDB AUTO_INCREMENT=372 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='消息消费成功表 幂等性';
# sql 消费消息一致表
CREATE TABLE `xy_kafka_out_msg` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`fw_bh` bigint(20) NOT NULL COMMENT '档案号',
`deal_flag` tinyint(2) NOT NULL DEFAULT '0' COMMENT '处理标记 0 失败 1 成功',
`gmt_create` datetime NOT NULL COMMENT '创建时间',
`gmt_update` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `fwbh` (`fw_bh`) USING BTREE COMMENT '服务唯一标示'
) ENGINE=InnoDB AUTO_INCREMENT=715 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='任务添加进kafka队列 幂等性';
- pom文件依赖关系,集成了mybatis,generator,kafka,druid和lombok等
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<!-- <relativePath/> <!– lookup parent from repository –>-->
</parent>
<groupId>com.xy</groupId>
<artifactId>kafka</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>kafka</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
- generatorConfig.xml 配置内容(先生产对应消息一致性的表吗,是吧)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="MySqlTables" targetRuntime="MyBatis3" defaultModelType="flat">
<!-- 关闭注解信息 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 自己修改JDBC的路径 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- model的配置 -->
<javaModelGenerator targetPackage="com.xy.kafka.bean"
targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- mybatis的xml的配置 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成的dao类 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.xy.kafka.dao"
targetProject="src/main/java/">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="xy_kafka_in_msg" domainObjectName="XyKafkaInMsg"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
<generatedKey column="id" sqlStatement="JDBC" identity="true"/>
</table>
<table tableName="xy_kafka_out_msg" domainObjectName="XyKafkaOutMsg"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
<generatedKey column="id" sqlStatement="JDBC" identity="true"/>
</table>
</context>
</generatorConfiguration>
根据自己的数据库配置信息修改,配置之后使用idea自带的工具或者使用命令使用
maven 命令:
mybatis-generator:generate –e
5. 创建一个消息生产者,此处定时创建消息
package com.xy.kafka.schedule;
import com.xy.kafka.bean.XyKafkaInMsg;
import com.xy.kafka.constant.Topic;
import com.xy.kafka.dao.XyKafkaInMsgMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.Date;
import java.util.UUID;
/**
* @author liBai
* @Classname MsgProducer
* @Description TODO
* @Date 2019-05-14 17:08
*/
@Slf4j
@Component
@EnableScheduling
public class MsgProducer {
@Autowired
private KafkaTemplate kafkaTemplate;
@Autowired
private XyKafkaInMsgMapper inMsgMapper;
@Scheduled(cron = "0/10 * * * * ?")
public void send() {
String message = UUID.randomUUID().toString();
ListenableFuture listenableFuture = kafkaTemplate.send(Topic.SIMPLE,message);
listenableFuture.addCallback(
o -> log.info("消息发送成功,{}", o.toString()),
throwable -> log.info("消息发送失败,{}" + throwable.getMessage())
);
XyKafkaInMsg build = new XyKafkaInMsg();
build.setFwBh(System.currentTimeMillis());
build.setGmtCreate(new Date());
XyKafkaInMsg inMsg = inMsgMapper.selectByFuBh(build.getFwBh());
if (inMsg == null){
int saveMsgResult = inMsgMapper.insertSelective(build);
log.info("消息插入结果:{}",saveMsgResult == 1 ? "成功" : "失败");
}
}
}
- 创建一个消息消费者消费消息
package com.xy.kafka.consumer;
import com.xy.kafka.constant.Topic;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
/**
* @author liBai
* @Classname KafkaSimpleConsumer
* @Description 单个消费者
* @Date 2019-05-14 10:08
*/
@Slf4j
@Component
public class KafkaSimpleConsumer {
// 简单消费者
@KafkaListener(groupId = "simpleGroup", topics = Topic.SIMPLE)
public void consumer1_1(ConsumerRecord<String, Object> record, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic, Consumer consumer, Acknowledgment ack) {
log.info("单独消费者消费消息,topic= {} ,content = {}",topic,record.value());
log.info("consumer content = {}",consumer);
ack.acknowledge();
/*
* 如果需要手工提交异步 consumer.commitSync();
* 手工同步提交 consumer.commitAsync()
*/
}
}
- application.yml 配置生产者消费者详细配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 配置当前要使用的数据源的操作类型
driver-class-name: com.mysql.cj.jdbc.Driver # 配置MySQL的驱动程序类
url: jdbc:mysql://192.168.1.200:3306/kafka?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 # 数据库连接地址
username: kafka # 数据库用户名
password: 123456 # 数据库连接密码
dbcp2: # 进行数据库连接池的配置
min-idle: 5 # 数据库连接池的最小维持连接数
initial-size: 5 # 初始化提供的连接数
max-total: 5 # 最大的连接数
max-wait-millis: 200 # 等待连接获取的最大超时时间
kafka:
# 以逗号分隔的地址列表,用于建立与Kafka集群的初始连接(kafka 默认的端口号为9092)
bootstrap-servers: 192.168.1.200:9092
producer:
# 发生错误后,消息重发的次数。
retries: 0
#当有多个消息需要被发送到同一个分区时,生产者会把它们放在同一个批次里。该参数指定了一个批次可以使用的内存大小,按照字节数计算。
batch-size: 16384
# 设置生产者内存缓冲区的大小。
buffer-memory: 33554432
# 键的序列化方式
key-serializer: org.apache.kafka.common.serialization.StringSerializer
# 值的序列化方式
value-serializer: org.apache.kafka.common.serialization.StringSerializer
# acks=0 : 生产者在成功写入消息之前不会等待任何来自服务器的响应。
# acks=1 : 只要集群的首领节点收到消息,生产者就会收到一个来自服务器成功响应。
# acks=all :只有当所有参与复制的节点全部收到消息时,生产者才会收到一个来自服务器的成功响应。
acks: 1
consumer:
# 自动提交的时间间隔 在spring boot 2.X 版本中这里采用的是值的类型为Duration 需要符合特定的格式,如1S,1M,2H,5D
auto-commit-interval: 1S
# 该属性指定了消费者在读取一个没有偏移量的分区或者偏移量无效的情况下该作何处理:
# latest(默认值)在偏移量无效的情况下,消费者将从最新的记录开始读取数据(在消费者启动之后生成的记录)
# earliest :在偏移量无效的情况下,消费者将从起始位置读取分区的记录
auto-offset-reset: earliest
# 是否自动提交偏移量,默认值是true,为了避免出现重复数据和数据丢失,可以把它设置为false,然后手动提交偏移量
enable-auto-commit: false
# 键的反序列化方式
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
# 值的反序列化方式
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
listener:
# 在侦听器容器中运行的线程数。
concurrency: 5
#listner负责ack,每调用一次,就立即commit
ack-mode: manual_immediate
server:
port: 8081
# mybatis.config-location=classpath:mybatis/mybatis-config.xml
# mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis:
mapper-locations: classpath:mapper/*.xml
logging:
level:
com.xy.kafka : debug
- 项目整体结构图展示,项目中还有使用消息一致性消费,生成外部调用生产消息消费消息的接口,具体见源码,这里就不一一展示了,有问题欢迎留言