SpringBoot整合Kafka
第一步:添加依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/>
</parent>
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
第二步:代码实现
@RestController
@SpringBootApplication
@RequestMapping
public class KafkaApplication {
private static final Logger logger = LoggerFactory.getLogger(KafkaApplication.class);
public static void main(String[] args) {
SpringApplication.run(KafkaApplication.class, args);
}
@RequestMapping("/index")
public String index() {
return "Hello,Kafka!";
}
@Autowired
private KafkaTemplate template;
private static final String topic = "kafkaDemo";
@GetMapping("/send/{input}")
public String sendToKafka(@PathVariable String input) {
this.template.send(topic, input);
return "send success";
}
@GetMapping("/send/{input}")
public String sendTranceKafka(@PathVariable String input) throws ExecutionException, InterruptedException{
template.executeInTransaction(t->{
t.send(topic, input);
if ("error".equals(input)) {
throw new RuntimeException("input is error");
}
t.send(topic, input + "anthor");
return true;
});
return "success";
}
@KafkaListener(id = "", topics = topic, groupId = "group.demo")
public void listener(String input) {
logger.info("input value:{}", input);
}
@GetMapping("/sendMessage/{input}")
@Transactional(rollbackFor = RuntimeException.class)
public String sendTranceMessage(@PathVariable String input) throws ExecutionException, InterruptedException{
template.send(topic, input);
if ("error".equals(input)) {
throw new RuntimeException("input is error");
}
template.send(topic, input + " anthor");
return "send success";
}
}
spring.kafka.producer.bootstrap-servers=192.168.247.188:9092
spring.kafka.consumer.bootstrap-servers=192.168.247.188:9092
# 事务支持
spring.kafka.producer.transaction-id-prefix=kafka_tx.