如何在spring事務(wù)提交之后進(jìn)行異步操作
問(wèn)題
業(yè)務(wù)場(chǎng)景
業(yè)務(wù)需求上經(jīng)常會(huì)有一些邊緣操作,比如主流程操作A:用戶報(bào)名課程操作入庫(kù),邊緣操作B:發(fā)送郵件或短信通知。
業(yè)務(wù)要求
- 操作A操作數(shù)據(jù)庫(kù)失敗后,事務(wù)回滾,那么操作B不能執(zhí)行。
- 操作A執(zhí)行成功后,操作B也必須執(zhí)行成功
如何實(shí)現(xiàn)
普通的執(zhí)行A,之后執(zhí)行B,是可以滿足要求1,對(duì)于要求2通常需要設(shè)計(jì)補(bǔ)償?shù)牟僮?/p>
一般邊緣的操作,通常會(huì)設(shè)置成為異步的,以提升性能,比如發(fā)送MQ,業(yè)務(wù)系統(tǒng)負(fù)責(zé)事務(wù)成功后消息發(fā)送成功,然后接收系統(tǒng)負(fù)責(zé)保證通知成功完成
要點(diǎn)
如何在spring事務(wù)提交之后操作
如何把操作異步化
實(shí)現(xiàn)方案
使用TransactionSynchronizationManager在事務(wù)提交之后操作
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");
}該方法就可以實(shí)現(xiàn)在事務(wù)提交之后進(jìn)行操作
操作異步化
使用mq或線程池來(lái)進(jìn)行異步,比如使用線程池:
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");
}封裝以上兩步
對(duì)于第二步來(lái)說(shuō),如果這類方法比較多的話,則寫(xiě)起來(lái)重復(fù)性太多,因而,抽象出來(lái)如下:
這里改造了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");
}關(guān)于Spring的Async
spring為了方便應(yīng)用使用線程池進(jìn)行異步化,默認(rèn)提供了@Async注解,可以整個(gè)app使用該線程池,而且只要一個(gè)@Async注解在方法上面即可,省去重復(fù)的submit操作。關(guān)于async要注意的幾點(diǎn):
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" />這個(gè)必須配置在root context里頭,而且web context不能掃描controller層外的注解,否則會(huì)覆蓋掉。
<context:component-scan base-package="com.yami.web.controller"/> <mvc:annotation-driven/>
2、async的調(diào)用問(wèn)題
async方法的調(diào)用,不能由同類方法內(nèi)部調(diào)用,否則攔截不生效,這是spring默認(rèn)的攔截問(wèn)題,必須在其他類里頭調(diào)用另一個(gè)類中帶有async的注解方法,才能起到異步效果。
3、事務(wù)問(wèn)題
async方法如果也開(kāi)始事務(wù)的話,要注意事務(wù)傳播以及事務(wù)開(kāi)銷的問(wèn)題。而且在async方法里頭使用如上的TransactionSynchronizationManager.registerSynchronization不起作用,值得注意。
以上就是如何在spring事務(wù)提交之后進(jìn)行異步操作的詳細(xì)內(nèi)容,更多關(guān)于spring數(shù)據(jù)庫(kù)事務(wù)提交異步操作的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java時(shí)間處理第三方包Joda?Time使用詳解
這篇文章主要為大家介紹了Java時(shí)間處理第三方包Joda?Time使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
使用IDEA和Gradle構(gòu)建Vertx項(xiàng)目(圖文步驟)
這篇文章主要介紹了使用IDEA和Gradle構(gòu)建Vertx項(xiàng)目(圖文步驟),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-09-09
SpringBoot重寫(xiě)addResourceHandlers映射文件路徑方式
這篇文章主要介紹了SpringBoot重寫(xiě)addResourceHandlers映射文件路徑方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Springboot使用@WebListener?作為web監(jiān)聽(tīng)器的過(guò)程解析
這篇文章主要介紹了Springboot使用@WebListener作為web監(jiān)聽(tīng)器的過(guò)程,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08
MyBatis使用logback包打印SQL語(yǔ)句實(shí)踐
文章介紹了如何在Java項(xiàng)目中使用Maven管理依賴,并配置Logback來(lái)打印SQL語(yǔ)句,通過(guò)修改logback.xml文件,可以將SQL語(yǔ)句以XML格式輸出,便于調(diào)試和分析2026-01-01
Java編程刪除鏈表中重復(fù)的節(jié)點(diǎn)問(wèn)題解決思路及源碼分享
這篇文章主要介紹了Java編程刪除鏈表中重復(fù)的節(jié)點(diǎn)問(wèn)題解決思路及源碼分享,具有一定參考價(jià)值,這里分享給大家,供需要的朋友了解。2017-10-10
解決try-catch捕獲異常信息后Spring事務(wù)失效的問(wèn)題
這篇文章主要介紹了解決try-catch捕獲異常信息后Spring事務(wù)失效的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
IKAnalyzer結(jié)合Lucene實(shí)現(xiàn)中文分詞(示例講解)
下面小編就為大家?guī)?lái)一篇IKAnalyzer結(jié)合Lucene實(shí)現(xiàn)中文分詞(示例講解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-10-10

