SpringBoot异步线程配置
1. 配置文件
async:
executor:
corePoolSize: 10
maxPoolSize: 100
queueCapacity: 1000
keepAliveSeconds: 60
threadNamePrefix: xpf-thread-
2.配置类
package com.xpf.config.executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
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 {
@Value("${async.executor.corePoolSize}")
private Integer corePoolSize;
@Value("${async.executor.maxPoolSize}")
private Integer maxPoolSize;
@Value("${async.executor.queueCapacity}")
private Integer queueCapacity;
@Value("${async.executor.keepAliveSeconds}")
private Integer keepAliveSeconds;
@Value("${async.executor.threadNamePrefix}")
private String threadNamePrefix;
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setThreadNamePrefix(threadNamePrefix);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
3.使用
@Async
public void test(){
}