Spring Boot 编程式事务 TransactionTemplate

Spring Boot 事务 About 1,337 words

备注

不会触发Spring Event,按需手动发送。

代码

import org.springframework.transaction.support.TransactionTemplate;

@Resource
private TransactionTemplate transactionTemplate;

transactionTemplate.executeWithoutResult(transactionStatus -> {
    try {
        // Logic
    } catch (Throwable e) {
        log.error("error: {}", e.getMessage(), e);
        transactionStatus.setRollbackOnly();
        throw e;
    }
})

注册事务同步事件

transactionTemplate执行完事务后会触发事件,等同于发送Spring Event事件。

transactionTemplate.executeWithoutResult(transactionStatus -> {
    log.info("add start");
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
        @Override
        public void afterCommit() {
            //做你想做的业务
            System.out.println("afterCommit#" + Thread.currentThread().getId() + " " + Thread.currentThread().getName());
        }

        @Override
        public void afterCompletion(int status) {
            // int STATUS_COMMITTED = 0;
            // int STATUS_ROLLED_BACK = 1;
            // int STATUS_UNKNOWN = 2;
            System.out.println("afterCompletion#" + status + ": " + Thread.currentThread().getId() + " " + Thread.currentThread().getName());
        }
    });
});
Views: 111 · Posted: 2024-05-30

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh