Files
fadada/src/main/java/com/example/sso/config/AsyncConfig.java
2025-08-22 14:36:10 +08:00

54 lines
2.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.example.sso.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.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
// ThredPoolTaskExcutor的处理流程
// 当池子大小小于corePoolSize就新建线程并处理请求
// 当池子大小等于corePoolSize把请求放入workQueue中池子里的空闲线程就去workQueue中取任务并处理
// 当workQueue放不下任务时就新建线程入池并处理请求如果池子大小撑到了maximumPoolSize就用RejectedExecutionHandler来做拒绝处理
// 当池子的线程数大于corePoolSize时多余的线程会等待keepAliveTime长时间如果无请求可处理就自行销毁
@Override
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数:线程池创建的时候初始化的线程数
executor.setCorePoolSize(30);
// 最大线程数:线程池最大的线程数,只有缓冲队列满了之后才会申请超过核心线程数的线程
executor.setMaxPoolSize(100);
// 缓冲队列:用来缓冲执行任务的队列
executor.setQueueCapacity(50);
// 线程池关闭:等待所有任务都完成再关闭
executor.setWaitForTasksToCompleteOnShutdown(true);
// 等待时间等待5秒后强制停止
executor.setAwaitTerminationSeconds(5);
// 允许空闲时间超过核心线程之外的线程到达60秒后会被销毁
executor.setKeepAliveSeconds(60);
// 线程名称前缀
executor.setThreadNamePrefix("fadada");
// 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程)
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化线程
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}