Java异步事务

有一个数据分析的接口特别耗时,请求一次要大约半小时才能出结果。

于是,我对它这样处理:请求这个接口后,将其直接异步执行,并直接向前端返回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 }

好啦,这样就大功告成了~

 

参考:

异步事务?关于异步@Async + 事务@Transactional的结合使用问题分析【享学Spring MVC】

posted on 2021-06-27 20:59  chenyangsocool  阅读(2183)  评论(0编辑  收藏  举报