异步线程解决seata事务1000问题
原因:seata1.5.0
以下版本,事务执行sql超过1000,会抛出异常。
解决方案:部分sql使用异步线程。
实现方式:
1、初始化异步线程池
@Configuration
@EnableAsync
public class ThreadAsyncConfig implements AsyncConfigurer {
/**
* 线程配置参数
*/
@Autowired
private ThreadPollConfigProperties threadPollConfigProperties;
@Bean("threadPoolTaskAsyncExecutor")
public ThreadPoolTaskExecutor threadPoolTaskAsyncExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
// 核心线程数
threadPoolTaskExecutor.setCorePoolSize(3);
// 最大线程数
threadPoolTaskExecutor.setMaxPoolSize(10);
// 队列容量大小
threadPoolTaskExecutor.setQueueCapacity(threadPollConfigProperties.getCapacity());
// 是否允许核心线程超时
threadPoolTaskExecutor.setAllowCoreThreadTimeOut(threadPollConfigProperties.getAllowCoreThreadTimeOut());
// 线程保活时间
threadPoolTaskExecutor.setKeepAliveSeconds(threadPollConfigProperties.getKeepAliveTime());
// 线程命名前缀规则
threadPoolTaskExecutor.setThreadNamePrefix(threadPollConfigProperties.getThreadNamePrefix());
// 等待终止时间(秒)
threadPoolTaskExecutor.setAwaitTerminationSeconds(threadPollConfigProperties.getAwaitTerminationSeconds());
/**
* 线程池满了之后如何处理:默认是 new AbortPolicy();
* (1) ThreadPoolExecutor.AbortPolicy 处理程序遭到拒绝将抛出运行时RejectedExecutionException;
* (2) ThreadPoolExecutor.CallerRunsPolicy 线程调用运行该任务的 execute 本身。此策略提供简单的反馈控制机制,能够减缓新任务的提交速度
* (3) ThreadPoolExecutor.DiscardPolicy 不能执行的任务将被删除;
* (4) ThreadPoolExecutor.DiscardOldestPolicy 如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程)。
*/
switch (threadPollConfigProperties.getRejectedExecutionHandler()){
case "AbortPolicy":
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
break;
case "CallerRunsPolicy":
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
break;
case "DiscardPolicy":
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
break;
case "DiscardOldestPolicy":
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
break;
default:
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
break;
}
// 初始化线程池
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
2、在启动类添加@EnableAsync
注解。
3、创建异步线程服务类,并使用AsyncService asyncService= (AsyncService) AopContext.currentProxy();
调用服务类方法。
注意:不可以在其他bean中使用@Autorwire
或@Reource
注入AsyncService
。