一,创建工程项目
第一步,填写项目信息
第二步
项目结构
二、项目的代码
2.1 给出application.properties的代码
server.port=8081
logging.level.root=INFO
# 生产者
spring.kafka.producer.bootstrap-servers=192.168.0.183:9092
# 消费者
spring.kafka.consumer.bootstrap-servers=192.168.0.183:9092
# 事务支持
spring.kafka.producer.transaction-id-prefix=kafka_tx.
2.2 给出pom.xml代码
注意这里的kafka依赖版本
<?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 https://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.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.demo.kafka</groupId>
<artifactId>demo-kafka</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.4.3.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.3 给出KafkaController的代码
/**
* @program: test1-kafka
* @description: kafka事务的使用
* @author: WEN
* @create: 2020-08-04
**/
@RestController
@RequestMapping
public class KafkaController {
private static final Logger logger = LoggerFactory.getLogger(KafkaController.class);
@Autowired
private KafkaTemplate template;
private static final String topic = "xiaomo";
@RequestMapping("index")
public String index(){
return "hello,kafka!";
}
/** * 发送消息
*/
@GetMapping("/send/{input}")
@Transactional(rollbackFor = RuntimeException.class)
public String sendToKafka(@PathVariable String input) {
//事务的支持
template.send(topic,input);
if ("error".equals(input)){
throw new RuntimeException("this is a error!!!!!!");
}
template.send(topic,input+" mmmmmm");
return "send success!"+input;
}
/** * 接收消息 */
@KafkaListener(id = "", topics = topic, groupId = "group.demo")
public void listener(String input) {
logger.info("input value:{}", input);
}
}
三、项目启动测试
3.1 测试index能否正常显示
3.2 测试生产者跟消费者
首先输入一个不是error的字符串
查看控制台打印
可以看到有两条消息,消费者接收到,并且打印出来了
可以看一下虚拟机的消费端
3.3 测试error
可以看到页面报500,证明抛出了异常
正常的话,此时应该只有一条消息被发送了
去控制台看一下
发现没有打印
是因为加了事务的原因,进行了回滚,就是一个不成功,所有都没有发送了