使用步骤一:在application.properties中添加线程池配置。
#ThreadPool
spring.task.pool.corePoolSize = 60
spring.task.pool.maxPoolSize = 100
spring.task.pool.keepAliveSecond = 120
spring.task.pool.queueCapacity = 5
spring.task.pool.encoding.force = true
spring.task.pool.encoding.charset = UTF-8
spring.task.pool.encoding.enabled = true
spring.task.pool.encoding.uri-encoding = UTF-8
步骤二:编写线程配置参数类TaskThreadPoolConfig。
@Component
@Data
@ConfigurationProperties(prefix = "spring.task.pool")
public class TaskThreadPoolConfig implements AsyncConfigurer{
private int corePoolSize;
private int maxPoolSize;
private int keepAliveSeconds;
private int queueCapacity;
}
步骤三:初始化线程池。
@Configuration
@EnalbeAsync
public class TaskExecutePool{
@Autowried
private TaskThreadPoolConfig threadPool;
@Bean("myTaskAsyncPool")
public Executor myTaskAsyncPool(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(threadPool.getCorePoolSize);
executor.setMaxPoolSize(threadPool.getMaxPoolSize);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.setQueueCapacity(threadPool.getQueueCapacity);
executor.setKeepAliveSeconds(threadPool.getKeepAliveSeconds());
executor.setThreadNamePrefix("MyExecutor---");
//rejection-policy:当pool达到max size的时候,如何处理新任务
//CALLER_RUNS:不在新任务中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
步骤四:创建异步任务。
@Slf4j
@Service
public class ThreadTask{
@Async("myTaskAsyncPool")
public CompletableFuture getMethod(){
try{
//可在此处添加业务逻辑
sleep(3000);
}catch(Exception e){
e.printStackTrace();
}
//可传异步任务返回结果
return CompletableFuture.completedFuture("自行传值");
}
}