Spring-kafka introductory learning (5): spring-kafka transaction

I. Introduction

spring-kafka provides two ways to implement transactions

1. Use SpringBoot's annotation @Transactional

2. Local affairs KafkaTemplate

二、@Transactional

Modify the configuration of the producer and enable transaction support

 @Bean
    public ProducerFactory<Integer, String> producerFactory() {
        DefaultKafkaProducerFactory<Integer, String> factory = new DefaultKafkaProducerFactory<>(producerConfigs());
        factory.setTransactionIdPrefix("trans-");//支持事务
        return factory;
    }
    @Bean
    KafkaTransactionManager kafkaTransactionManager() {
        return new KafkaTransactionManager(producerFactory());
    }

interface

    @RequestMapping(value = "test3")
    @Transactional
    public String test3() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        kafkaTemplate.send("topic_transaction_test", 0, "事务测试数据" + sdf.format(new Date()));
        kafkaTemplate.flush();
        throw new RuntimeException("a");
//        return "test";
    }

Three, local affairs KafkaTemplate

Modify the configuration of the producer and enable transaction support (just set this one)

    @Bean
    public ProducerFactory<Integer, String> producerFactory() {
        DefaultKafkaProducerFactory<Integer, String> factory = new DefaultKafkaProducerFactory<>(producerConfigs());
        factory.setTransactionIdPrefix("trans-");//支持事务
        return factory;
    }

Use of local affairs

        kafkaTemplate.executeInTransaction(new KafkaOperations.OperationsCallback() {
            @Override
            public Object doInOperations(KafkaOperations kafkaOperations) {
                kafkaOperations.send("topic_transaction_test", 0, "事务测试数据" + sdf.format(new Date()));
                throw new RuntimeException("a");
//                return true;
            }
        });

 

Guess you like

Origin blog.csdn.net/cs373616511/article/details/106099834