springboot异步线程池配置
springboot异步线程池配置
package com.sangfor.api.config;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.DefaultManagedAwareThreadFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.validation.constraints.NotNull;
import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author: xmz
*/
@EnableAsync
@EnableScheduling
@Configuration
public class AsyncConfig implements AsyncConfigurer {
private static final int MAX_SIZE = 500;
private static final int QUEUE_SIZE = 500;
private static final int KEEP_ALIVE_SECOND = 600;
private static final int AWAIT_TERMINAL_SECOND = 60;
private static final int CORE_SIZE = Runtime.getRuntime().availableProcessors() * 2;
@Bean
@Override
public ThreadPoolTaskExecutor getAsyncExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setMaxPoolSize(MAX_SIZE);
pool.setCorePoolSize(CORE_SIZE);
pool.setQueueCapacity(QUEUE_SIZE);
pool.setKeepAliveSeconds(KEEP_ALIVE_SECOND);
pool.setAllowCoreThreadTimeOut(false);
pool.setThreadFactory(new DefaultManagedAwareThreadFactory());
/*
*线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,
*表示当线程池没有处理能力的时候,该策略会直接在execute方法的调用线程中运行这个任务;
*如果执行程序已关闭,则会丢弃该任务
*/
pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
pool.setThreadNamePrefix("async-aip-");
// 该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住。
pool.setWaitForTasksToCompleteOnShutdown(true);
pool.setAwaitTerminationSeconds(AWAIT_TERMINAL_SECOND);
//初始化线程池
pool.initialize();
return pool;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
@Bean
protected WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void configureAsyncSupport(@NotNull AsyncSupportConfigurer configurer) {
configurer.setTaskExecutor(Objects.requireNonNull(getAsyncExecutor()));
}
};
}
}
分类:
springboot
标签:
异步线程池配置
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)