如何在spring事務提交之后進行異步操作
問題
業(yè)務場景
業(yè)務需求上經(jīng)常會有一些邊緣操作,比如主流程操作A:用戶報名課程操作入庫,邊緣操作B:發(fā)送郵件或短信通知。
業(yè)務要求
- 操作A操作數(shù)據(jù)庫失敗后,事務回滾,那么操作B不能執(zhí)行。
- 操作A執(zhí)行成功后,操作B也必須執(zhí)行成功
如何實現(xiàn)
普通的執(zhí)行A,之后執(zhí)行B,是可以滿足要求1,對于要求2通常需要設計補償?shù)牟僮?/p>
一般邊緣的操作,通常會設置成為異步的,以提升性能,比如發(fā)送MQ,業(yè)務系統(tǒng)負責事務成功后消息發(fā)送成功,然后接收系統(tǒng)負責保證通知成功完成
要點
如何在spring事務提交之后操作
如何把操作異步化
實現(xiàn)方案
使用TransactionSynchronizationManager在事務提交之后操作
public void insert(TechBook techBook){ bookMapper.insert(techBook); // send after tx commit but is async TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { System.out.println("send email after transaction commit..."); } } ); ThreadLocalRandom random = ThreadLocalRandom.current(); if(random.nextInt() % 2 ==0){ throw new RuntimeException("test email transaction"); } System.out.println("service end"); }
該方法就可以實現(xiàn)在事務提交之后進行操作
操作異步化
使用mq或線程池來進行異步,比如使用線程池:
private final ExecutorService executorService = Executors.newFixedThreadPool(5); public void insert(TechBook techBook){ bookMapper.insert(techBook); // send after tx commit but is async TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { executorService.submit(new Runnable() { @Override public void run() { System.out.println("send email after transaction commit..."); try { Thread.sleep(10*1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("complete send email after transaction commit..."); } }); } } ); // async work but tx not work, execute even when tx is rollback // asyncService.executeAfterTxComplete(); ThreadLocalRandom random = ThreadLocalRandom.current(); if(random.nextInt() % 2 ==0){ throw new RuntimeException("test email transaction"); } System.out.println("service end"); }
封裝以上兩步
對于第二步來說,如果這類方法比較多的話,則寫起來重復性太多,因而,抽象出來如下:
這里改造了azagorneanu的代碼:
public interface AfterCommitExecutor extends Executor { } import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Component public class AfterCommitExecutorImpl extends TransactionSynchronizationAdapter implements AfterCommitExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(AfterCommitExecutorImpl.class); private static final ThreadLocal<List<Runnable>> RUNNABLES = new ThreadLocal<List<Runnable>>(); private ExecutorService threadPool = Executors.newFixedThreadPool(5); @Override public void execute(Runnable runnable) { LOGGER.info("Submitting new runnable {} to run after commit", runnable); if (!TransactionSynchronizationManager.isSynchronizationActive()) { LOGGER.info("Transaction synchronization is NOT ACTIVE. Executing right now runnable {}", runnable); runnable.run(); return; } List<Runnable> threadRunnables = RUNNABLES.get(); if (threadRunnables == null) { threadRunnables = new ArrayList<Runnable>(); RUNNABLES.set(threadRunnables); TransactionSynchronizationManager.registerSynchronization(this); } threadRunnables.add(runnable); } @Override public void afterCommit() { List<Runnable> threadRunnables = RUNNABLES.get(); LOGGER.info("Transaction successfully committed, executing {} runnables", threadRunnables.size()); for (int i = 0; i < threadRunnables.size(); i++) { Runnable runnable = threadRunnables.get(i); LOGGER.info("Executing runnable {}", runnable); try { threadPool.execute(runnable); } catch (RuntimeException e) { LOGGER.error("Failed to execute runnable " + runnable, e); } } } @Override public void afterCompletion(int status) { LOGGER.info("Transaction completed with status {}", status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK"); RUNNABLES.remove(); } } public void insert(TechBook techBook){ bookMapper.insert(techBook); // send after tx commit but is async // TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { // @Override // public void afterCommit() { // executorService.submit(new Runnable() { // @Override // public void run() { // System.out.println("send email after transaction commit..."); // try { // Thread.sleep(10*1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // System.out.println("complete send email after transaction commit..."); // } // }); // } // } // ); //send after tx commit and is async afterCommitExecutor.execute(new Runnable() { @Override public void run() { try { Thread.sleep(5*1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("send email after transactioin commit"); } }); // async work but tx not work, execute even when tx is rollback // asyncService.executeAfterTxComplete(); ThreadLocalRandom random = ThreadLocalRandom.current(); if(random.nextInt() % 2 ==0){ throw new RuntimeException("test email transaction"); } System.out.println("service end"); }
關于Spring的Async
spring為了方便應用使用線程池進行異步化,默認提供了@Async注解,可以整個app使用該線程池,而且只要一個@Async注解在方法上面即可,省去重復的submit操作。關于async要注意的幾點:
1、async的配置
<context:component-scan base-package="com.yami" /> <!--配置@Async注解使用的線程池,這里的id隨便命名,最后在task:annotation-driven executor= 指定上就可以--> <task:executor id="myExecutor" pool-size="5"/> <task:annotation-driven executor="myExecutor" />
這個必須配置在root context里頭,而且web context不能掃描controller層外的注解,否則會覆蓋掉。
<context:component-scan base-package="com.yami.web.controller"/> <mvc:annotation-driven/>
2、async的調(diào)用問題
async方法的調(diào)用,不能由同類方法內(nèi)部調(diào)用,否則攔截不生效,這是spring默認的攔截問題,必須在其他類里頭調(diào)用另一個類中帶有async的注解方法,才能起到異步效果。
3、事務問題
async方法如果也開始事務的話,要注意事務傳播以及事務開銷的問題。而且在async方法里頭使用如上的TransactionSynchronizationManager.registerSynchronization不起作用,值得注意。
以上就是如何在spring事務提交之后進行異步操作的詳細內(nèi)容,更多關于spring數(shù)據(jù)庫事務提交異步操作的資料請關注腳本之家其它相關文章!
相關文章
jboss( WildFly)上運行 springboot程序的步驟詳解
這篇文章主要介紹了jboss( WildFly)上運行 springboot程序的步驟詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02Java 仿天貓服裝商城系統(tǒng)的實現(xiàn)流程
讀萬卷書不如行萬里路,只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+jsp+mysql+maven實現(xiàn)一個仿天貓服裝商城系統(tǒng),大家可以在過程中查缺補漏,提升水平2021-11-11springboot集成springsession如何實現(xiàn)分布式session共享
這篇文章主要介紹了springboot集成springsession如何實現(xiàn)分布式session共享問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09防止SpringMVC攔截器攔截js等靜態(tài)資源文件的解決方法
本篇文章主要介紹了防止SpringMVC攔截器攔截js等靜態(tài)資源文件的解決方法,具有一定的參考價值,有興趣的同學可以了解一下2017-09-09