1、Kafka 事务消息通过配置文件设置开启,设置方法如下:
transaction-id-prefix: transaction-id-
2、使用@Transactional 注解,在类或者方法上使用
public interface SendMessageService { void sendTransactionMessage(String message);}
@Service@Transactional(rollbackFor = Exception.class)public class SendMessageServiceImpl implements SendMessageService { @Resource private KafkaTemplate kafkaTemplate; @Override public void sendTransactionMessage(String message) { System.out.println(message); for (int i = 1; i < 10; i++) { OrderMsg orderMsg = new OrderMsg(i+"", i+"-"+message); kafkaTemplate.send("topic08", orderMsg); kafkaTemplate.flush(); if (i==5) { int j = 1/0; } } }}
3、实现一个接口,方便进行测试
@GetMapping("/user/transaction/{message}")public void sendTransactionUserMessage(@PathVariable("message") String message) { sendMessageService.sendTransactionMessage(message);}