Spring Kafka事务-没有事务正在处理中,请在template.executeInTransaction()的范



我正在尝试使用KafkaTemplate:从事务向Kafka发布消息

@Autowired
KafkaTemplate<GenericRecord, GenericRecord> kafkaTemplate;
@Transactional
@RabbitListener(queues = "queueName")
void input(final List<Message> messages) {
for (Message msg : messages) {
PublishRequest request = prepareRequest(msg);
kafkaTemplate.sendDefault(request.getKey(), reguest.getValue());
}
transactionalDatabaseInserts();
}

但当我这样做的时候,我会得到一个例外:

由java.lang.IollegalStateException引起:中没有事务过程可能的解决方案:在模板的作用域。executeInTransaction((操作,启动在调用模板方法之前与@Transactional进行事务处理,在侦听器容器启动的事务中运行记录

KafkaTemplate:的配置

@EnableTransactionManagement
@Configuration
public class KafkaConfig{
@Bean
KafkaTransactionManager<GenericRecord, GenericRecord> kafkaTransactionManager(final ProducerFactory<GenericRecord, GenericRecord> producerFactory) {
return new KafkaTransactionManager<>(producerFactory);
}
@Bean
KafkaTemplate<GenericRecord, GenericRecord> kafkaTemplate(final ProducerFactory<GenericRecord, GenericRecord> producerFactory) {
return new KafkaTemplate<>(producerFactory);
}
}

在我的application.yaml中,我包括:

spring.kafka.producer.transaction-id-prefix: tx-

我希望我的方法使用@Transactional而不是kafkaTemplate.executeInTransaction()。为什么我会得到那个例外?

您必须有错误的配置-这符合预期。。。

@SpringBootApplication
@EnableTransactionManagement
public class So63596919Application {
public static void main(String[] args) {
SpringApplication.run(So63596919Application.class, args);
}
@Autowired
private KafkaTemplate<String, String> template;
private final CountDownLatch latch = new CountDownLatch(1);
@Transactional
@RabbitListener(queues = "so63596919")
public void listen(List<String> in) throws InterruptedException {
System.out.println(in);
in.forEach(str -> this.template.send("so63596919", str));
System.out.println("Hit enter to exit listener and commit transaction");
this.latch.await();
}
@KafkaListener(id = "so63596919", topics = "so63596919")
public void listen(String in) {
System.out.println(in);
}
@Bean
public Queue queue() {
return new Queue("so63596919");
}
@Bean
public NewTopic topic() {
return TopicBuilder.name("so63596919").partitions(1).replicas(1).build();
}
@Bean
public ApplicationRunner runner(RabbitTemplate template, AbstractRabbitListenerContainerFactory<?> factory) {
factory.setBatchListener(true);
factory.setContainerCustomizer(container -> {
((SimpleMessageListenerContainer) container).setConsumerBatchEnabled(true);
container.setDeBatchingEnabled(true);
});
return args -> {
template.convertAndSend("so63596919", "foo");
template.convertAndSend("so63596919", "bar");
System.in.read();
this.latch.countDown();
};
}
}
spring.kafka.producer.transaction-id-prefix: tx-
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.properties.isolation.level=read_committed
spring.rabbitmq.listener.simple.batch-size=2

如果你能把你的项目精简成这样一个小例子,我可以看看哪里出了问题。

最新更新