采用kafkatemplate发送事务消息,需要配置地方
1. spring.kafka.producer.transaction-id-prefix=kafka-tran
2. spring.kafka.producer.retries=1 --这个必须大于0
这个头不为空,会在默认的producerfactory及kafkatemplate初始化中中用到
DefaultKafkaProducerFactory
public boolean transactionCapable() {
return this.transactionIdPrefix != null;
}
KafkaTemplate
public KafkaTemplate(ProducerFactory<K, V> producerFactory, boolean autoFlush) {
this.producerFactory = producerFactory;
this.autoFlush = autoFlush;
this.transactional = producerFactory.transactionCapable();
}
这样就可以发送带事务的消息了,不需要@Transtractional注解,且kafkaTemplate.send()等不带事务的消息是无法发送的,直接报异常
public void sendMessageTransactional() {
String jsonMessage = buildMessage();
//局部开启事务
kafkaTemplate.executeInTransaction(operations -> {
operations.send(topic, 1, "key2", jsonMessage);
return true;
});
logger.info("已发送事务消息。。。。");
}
还有一种在代码中初始化producerfactory,template,kafkatranctionalmanager的方法,另说。