有一個數據分析的接口特別耗時,請求一次要大約半小時才能出結果。
於是,我對它這樣處理:請求這個接口后,將其直接異步執行,並直接向前端返回true。當其執行完成后,自動向管理員郵箱發送一封郵件。
這時候我發現,常規添加@Transactional注解,異步事務無法生效。於是就有了下面的解決方法。
一、異步配置
1 import org.apache.tomcat.util.threads.ThreadPoolExecutor; 2 import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; 3 import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.scheduling.annotation.AsyncConfigurer; 6 import org.springframework.scheduling.annotation.EnableAsync; 7 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 8 9 import java.util.concurrent.Executor; 10 11 @EnableAsync 12 @Configuration 13 public class AsyncConfig implements AsyncConfigurer { 14 15 @Override 16 public Executor getAsyncExecutor() { 17 ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 18 executor.setCorePoolSize(10);//核心線程數 19 executor.setMaxPoolSize(20);//最大線程數 20 executor.setQueueCapacity(1000);//隊列大小 21 executor.setKeepAliveSeconds(300);//線程最大空閑時間 22 executor.setThreadNamePrefix("fsx-Executor-"); //指定用於新創建的線程名稱的前綴。 23 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//拒絕策略(一共四種,此處省略) 24 executor.initialize(); 25 return executor; 26 } 27 28 /** 29 * 異常處理器 30 * 31 * @return 異常處理器 32 */ 33 @Override 34 public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { 35 System.out.println("異常處理器!!你可以自定義異常處理器~"); 36 return new SimpleAsyncUncaughtExceptionHandler(); 37 } 38 }
二、使用異步事務
1 public class MyController { 2 3 private final ApplicationContext applicationContext; 4 5 public MyController(ApplicationContext applicationContext) { 6 this.applicationContext = applicationContext; 7 } 8 9 @PostMapping("/test") 10 @ApiOperation(value = "測試") 11 public Boolean test() { 12 applicationContext.getBean(MyController.class).saveWithTransactional(); 13 return true; 14 } 15 16 @Async 17 @Transactional 18 public void saveWithTransactional() { 19 //你需要異步事務的業務代碼 20 } 21 }
好啦,這樣就大功告成了~
參考: