package com.example.redistest.config;
import lombok.extern.slf4j.Slf4j;
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.ThreadPoolTaskExecutor;
import java.util.concurrent.*;
/**
* @ Description: 配置可定长线程数
* @ Author :daizy
* @ CreateDate : 2021-12-01$ $
* @ Version :1.0
*/
@Configuration
@EnableAsync
@EnableScheduling
@Slf4j
public class AsyncConfiguration implements AsyncConfigurer{
@Bean(name = "taskExecutor")
public ThreadPoolTaskExecutor getThreadExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
int i = Runtime.getRuntime().availableProcessors();//获取到服务器的cpu内核
log.info("cpu内核:{}",i);
taskExecutor.setCorePoolSize(20);//核心池大小
taskExecutor.setMaxPoolSize(50);//最大线程数
taskExecutor.setQueueCapacity(100);//队列程度
taskExecutor.setKeepAliveSeconds(10);//线程空闲时间
taskExecutor.setThreadNamePrefix("task");//线程前缀名称
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());//配置拒绝策略
return taskExecutor;
}
@Bean("asyExecutor")//异步线程
public Executor getAsyExecutor(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(2);//核心池大小
taskExecutor.setMaxPoolSize(3);//最大线程数
taskExecutor.setQueueCapacity(1);//队列程度
taskExecutor.setKeepAliveSeconds(10);//线程空闲时间
taskExecutor.setThreadNamePrefix("asy");//线程前缀名称
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());//配置拒绝策略
return taskExecutor;
}
}