Springboot 线程池配置
最近的项目里要手动维护线程池,然后看到一起开发的小伙伴直接用Java了,我坚信Springboot不可能没这功能,于是查了些资料,果然有,这里给一下。
首先我们都知道@Async标签能让方法异步执行,但是这个标签用的是Springboot默认的线程池,想自己实现线程池就要在项目里创建一个TaskExecutor或它的子类的Bean,像这样:
@Bean
public AsyncTaskExecutor threadPoolTaskExecutor(){
ThreadPoolTaskExecutor threadPoolTaskExecutor=new ThreadPoolTaskExecutor();
//加入此头后此线程池成为系统线程池
threadPoolTaskExecutor.setThreadNamePrefix("Anno-Executor");
threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return threadPoolTaskExecutor;
}
其中拒绝策略可以改为手动编写,像下面这样:
threadPoolTaskExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
}
});
JDK里提供了四种默认的策略,非常粗暴:
public static class CallerRunsPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code CallerRunsPolicy}.
*/
public CallerRunsPolicy() { }
/**
* Executes task r in the caller's thread, unless the executor
* has been shut down, in which case the task is discarded.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
}
/**
* A handler for rejected tasks that throws a
* {@code RejectedExecutionException}.
*/
public static class AbortPolicy implements RejectedExecutionHandler {
/**
* Creates an {@code AbortPolicy}.
*/
public AbortPolicy() { }
/**
* Always throws RejectedExecutionException.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
/**
* A handler for rejected tasks that silently discards the
* rejected task.
*/
public static class DiscardPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code DiscardPolicy}.
*/
public DiscardPolicy() { }
/**
* Does nothing, which has the effect of discarding task r.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}
/**
* A handler for rejected tasks that discards the oldest unhandled
* request and then retries {@code execute}, unless the executor
* is shut down, in which case the task is discarded.
*/
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code DiscardOldestPolicy} for the given executor.
*/
public DiscardOldestPolicy() { }
/**
* Obtains and ignores the next task that the executor
* would otherwise execute, if one is immediately available,
* and then retries execution of task r, unless the executor
* is shut down, in which case task r is instead discarded.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
}
- CallerRunsPolicy是让调用方法的线程自己运行。
- AbortPolicy丢弃任务抛出异常。
- DiscardPolicy:丢弃任务不报错。
- DiscardOldestPolicy:丢弃队列最前面任务,之后尝试执行。
顺便说一下,查源码可知,默认的策略是AbortPolicy,也就是最粗暴的那个,不过考虑到通常是不要让拒绝发生的,这里用粗暴的方案问题不大。为了实现方便配置,可以用yml对其进行配置:
@Component
@Data
@ConfigurationProperties("thread-pool-factory")
public class ThreadPoolFactory {
private int corePoolSize;
private int maxPoolSize;
private int queueCapacity;
private int keepAliveSeconds;
@Bean
public AsyncTaskExecutor threadPoolTaskExecutor(){
//......
}
}
这里@Data标签是lambok的标签,快速生成getter和setter用。以上Component构建好后,可以直接配置:
thread-pool-factory:
#IO密集型应用,线程数为2N+1
corePoolSize: 9
maxPoolSize: 18
queueCapacity: 100
keepAliveSeconds: 120
以上。
Springboot 线程池配置的更多相关文章
- SpringBoot 线程池配置 实现AsyncConfigurer接口方法
目的是: 通过实现AsyncConfigurer自定义线程池,包含异常处理 实现AsyncConfigurer接口对异常线程池更加细粒度的控制 *a) 创建线程自己的线程池 b) 对void ...
- Spring线程池配置模板设计(基于Springboot)
目录 线程池配置模板 基础的注解解释 常用配置参数 配置类设计 线程池使用 ThreadPoolTaskExecutor源码 线程池配置模板 springboot给我们提供了一个线程池的实现,它的底层 ...
- SpringBoot异步及线程池配置
异步方法注解@Async 在SpringBoot中进行异步处理,可以使用异步注解@Async和@EnableAsync. @Async注解表示异步,如:@Async("asyncServic ...
- SpringBoot线程池的创建、@Async配置步骤及注意事项
最近在做订单模块,用户购买服务类产品之后,需要进行预约,预约成功之后分别给商家和用户发送提醒短信.考虑发短信耗时的情况所以我想用异步的方法去执行,于是就在网上看见了Spring的@Async了. 但是 ...
- 玩转SpringBoot之定时任务@Scheduled线程池配置
序言 对于定时任务,在SpringBoot中只需要使用@Scheduled 这个注解就能够满足需求,它的出现也给我们带了很大的方便,我们只要加上该注解,并且根据需求设置好就可以使用定时任务了. 但是, ...
- springboot 线程池
我们常用ThreadPoolExecutor提供的线程池服务,springboot框架提供了@Async注解,帮助我们更方便的将业务逻辑提交到线程池中异步执行,今天我们就来实战体验这个线程池服务: 本 ...
- springboot线程池的使用和扩展(转)
springboot线程池的使用和扩展 我们常用ThreadPoolExecutor提供的线程池服务,springboot框架提供了@Async注解,帮助我们更方便的将业务逻辑提交到线程池中异步执行, ...
- springboot线程池的使用和扩展
我们常用ThreadPoolExecutor提供的线程池服务,springboot框架提供了@Async注解,帮助我们更方便的将业务逻辑提交到线程池中异步执行,今天我们就来实战体验这个线程池服务: 本 ...
- springboot线程池@Async的使用和扩展
我们常用ThreadPoolExecutor提供的线程池服务,springboot框架提供了@Async注解,帮助我们更方便的将业务逻辑提交到线程池中异步执行,今天我们就来实战体验这个线程池服务: 本 ...
随机推荐
- html5 canvas显示文字(写上5个字,纪念我那刚刚逝去的爱情)
<script type="text/javascript"> window.addEventListener('load',eventWindowLoaded,fal ...
- php-url地址加密
下面是可以将我们的url地址加密.确保我们提交的数据安全 以下是代码片段: <?php function keyED($txt,$encrypt_key) //定义一个keyED { $encr ...
- ML—机器学习常用包(持续更新….)
机器学习是计算机科学和统计学的边缘交叉领域,R关于机器学习的包主要包括以下几个方面: 1)神经网络(Neural Networks): nnet.AMORE以及neuralnet,nnet提供了最常见 ...
- c++刷题(39/100)笔试题3
题目1: 现在你需要用一台奇怪的打字机书写一封书信.信的每行只能容纳宽度为100的字符,也就是说如果写下某个字符会导致行宽超过100,那么就要另起一行书写 信的内容由a-z的26个小写字母构成,而每个 ...
- golang的sort研究
年前没钱,等发工资.就这么在公司耗着不敢回家,无聊看了下golang的sort源码 type Interface interface { // Len is the number of element ...
- elasticsearch代码片段,及工具类SearchEsUtil.java
ElasticSearchClient.java package com.zbiti.framework.elasticsearch.utils; import java.util.Arrays; i ...
- java 组合接口时的名字冲突
重载方法仅通过返回类型是区分不开的,在打算组合的不同接口中,尽量使用不同的方法名,否则可能导致混乱 //: interfaces/InterfaceCollision.java package obj ...
- GeoHash解析及java实现
GeoHash解析请参考这里: http://www.open-open.com/lib/view/open1417940079964.html java实现GeoHash,代码已注释. import ...
- js里size和length的区别
length: length是js的原生方法,用于获取元素的个数和对象的长度 var length = $(obj).length; size(): size()属于方法,只能作用于对象上,获取元素的 ...
- ReentrantLock和AQS
AQS(AbstractQueuedSynchronizer)是JDK1.5提供的一个用来构建锁和同步工具的框架,子类包括常用的ReentrantLock.CountDownLatch.Semapho ...