CompletableFuture vs Spring Transactions

前端 未结 2 731
梦如初夏
梦如初夏 2021-01-17 22:01

Idea

I have a processing method which takes in a list of items and processes them asynchronously using external web service. The process steps also

相关标签:
2条回答
  • 2021-01-17 22:09

    The reason of your problem is, as said above, that the transaction ends when the return of method process(..) is reached.

    What you can do, is create the transaction manually, that gives you full control over when it starts and ends.

    Remove @Transactional

    Autowire the TransactionManager then in process(..) :

        TransactionDefinition txDef = new DefaultTransactionDefinition();
        TransactionStatus txStatus = transactionManager.getTransaction(txDef);
        try {
        //do your stuff here like
            doWhateverAsync().then(transactionManager.commit(txStatus);)
        } catch (Exception e) {
            transactionManager.rollback(txStatus);
            throw e;
        }
    
    0 讨论(0)
  • 2021-01-17 22:18

    In case of Spring Boot Application , you need following configurations.

    The main application method should be annotated with @EnableAsync.

    @Async annotation should be on the top of method having @Transactional annotation. This is necessary to indicate processing will be taking place in child thread.

    0 讨论(0)
提交回复
热议问题