概述
1、重写spring默认的异步线程池,限制最大数,防止内存被干爆
import lombok.extern.slf4j.Slf4j;
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;
/**
* 重写spring默认的异步线程池,限制最大数,防止内存被干爆
*/
@Slf4j
@Configuration
@EnableAsync
public class SpringDefaultAsyncExecutor implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(1000);
executor.setKeepAliveSeconds(300);
executor.setThreadNamePrefix("spring-default-async-Executor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
2、 自定义线程池,方法调用
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* 自定义线程池
*/
@Slf4j
@Configuration
@EnableAsync
public class AsyncExecutor {
/**
* xxx调用此线程池
* @Async("xxxAsyncExecutor")
* @return
*/
@Bean
public Executor xxxAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数
executor.setCorePoolSize(3);
// 最大线程数
executor.setMaxPoolSize(5);
// 队列大小,1000个,可排队
executor.setQueueCapacity(1000);
//
executor.setWaitForTasksToCompleteOnShutdown(true);
// 线程名称前缀
executor.setThreadNamePrefix("async-xxx-Executor-");
executor.initialize();
return executor;
}
}
如果配置多个线程池,在AsyncExecutor 类中添加bean即可。
最后
以上就是要减肥灯泡为你收集整理的spring线程池的全部内容,希望文章能够帮你解决spring线程池所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复