最近的项目里要手动维护线程池,然后看到一起开发的小伙伴直接用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 线程池配置的更多相关文章

  1. SpringBoot 线程池配置 实现AsyncConfigurer接口方法

      目的是:  通过实现AsyncConfigurer自定义线程池,包含异常处理  实现AsyncConfigurer接口对异常线程池更加细粒度的控制 *a) 创建线程自己的线程池  b) 对void ...

  2. Spring线程池配置模板设计(基于Springboot)

    目录 线程池配置模板 基础的注解解释 常用配置参数 配置类设计 线程池使用 ThreadPoolTaskExecutor源码 线程池配置模板 springboot给我们提供了一个线程池的实现,它的底层 ...

  3. SpringBoot异步及线程池配置

    异步方法注解@Async 在SpringBoot中进行异步处理,可以使用异步注解@Async和@EnableAsync. @Async注解表示异步,如:@Async("asyncServic ...

  4. SpringBoot线程池的创建、@Async配置步骤及注意事项

    最近在做订单模块,用户购买服务类产品之后,需要进行预约,预约成功之后分别给商家和用户发送提醒短信.考虑发短信耗时的情况所以我想用异步的方法去执行,于是就在网上看见了Spring的@Async了. 但是 ...

  5. 玩转SpringBoot之定时任务@Scheduled线程池配置

    序言 对于定时任务,在SpringBoot中只需要使用@Scheduled 这个注解就能够满足需求,它的出现也给我们带了很大的方便,我们只要加上该注解,并且根据需求设置好就可以使用定时任务了. 但是, ...

  6. springboot 线程池

    我们常用ThreadPoolExecutor提供的线程池服务,springboot框架提供了@Async注解,帮助我们更方便的将业务逻辑提交到线程池中异步执行,今天我们就来实战体验这个线程池服务: 本 ...

  7. springboot线程池的使用和扩展(转)

    springboot线程池的使用和扩展 我们常用ThreadPoolExecutor提供的线程池服务,springboot框架提供了@Async注解,帮助我们更方便的将业务逻辑提交到线程池中异步执行, ...

  8. springboot线程池的使用和扩展

    我们常用ThreadPoolExecutor提供的线程池服务,springboot框架提供了@Async注解,帮助我们更方便的将业务逻辑提交到线程池中异步执行,今天我们就来实战体验这个线程池服务: 本 ...

  9. springboot线程池@Async的使用和扩展

    我们常用ThreadPoolExecutor提供的线程池服务,springboot框架提供了@Async注解,帮助我们更方便的将业务逻辑提交到线程池中异步执行,今天我们就来实战体验这个线程池服务: 本 ...

随机推荐

  1. docker重新安装后无法启动

    问题描述: docker版本升级或者重新安装后,无法启动服务,出现如下报错: level=error msg="[graphdriver] prior storage driver over ...

  2. TC-572-D1L2 (双向搜索+记忆化)

    solution: 这一题是比较难实现的双向搜索题:(字符串+双向搜索+hash记忆化) 我们可以先把K的前半部分枚举出来,并将得出的所有结果和题目给的n个数的每一个数的前半部分都比对一遍,得到它和每 ...

  3. NVIDIA / Intel 核芯显卡显示 + Nvidia 计算

    今天折腾了好久intel集成显卡显示.最后好不容易才全部搞定,这里记录一下.   1. 首先在BIOS里是要打开Intel 核芯显卡的.我把它设置成了主显卡,显示器也接到核心显卡的口上. 重启后, I ...

  4. Ubuntu下ibus在firefox浏览器中选中即删除的解决办法

    Ubuntu上的firefox更新到36版后,ibus在浏览器中输入中文时选中的文字就会被删除.这个问题在很多贴吧.论坛上也有讨论,不过很多方法都无效.最简单有效的办法就是在命令行输入 ibus-se ...

  5. 微信小程序实现首页图片多种排版布局!

    先来个效果图: 使用技术主要是flex布局,绝对定位布局,小程序前端页面开发,以及一些样式! 直接贴代码,都有详细注释,熟悉一下,方便以后小程序开发! wxml: <view class='in ...

  6. oracle 级联查询 根路径

    级联查询有很多教程示例,但是没有找到求特定子孙到根的路径的例子,折腾了一番总算想出方法了. 现假设我们拥有一个菜单表t_menu,其中只有三个字段:id.name和parent_id.它们是具有父子关 ...

  7. 总结WCF开发中遇到的几个问题

    最近的项目,需要用到WCF,在以前的工作中,经常是将WCF托管在IIS中,主要有几下几个原因:      第一:部署非常方便,和部署一个站点没什么区别:      第二:不受防火墙的影响,因为一般服务 ...

  8. java虚拟机规范(se8)——java虚拟机结构(三)

    2.6. 栈帧 栈帧用于存储数据和部分结果,同样也用于执行动态链接,返回方法的值和分派异常. 当方法被调用的时候会创建一个新的栈帧.当一个方法调用结束时,它对应的栈帧就被销毁了,不管是正常调用结束还是 ...

  9. 如何将同一个APP中的不同activity在Recent(最近任务)中显示?

    需求描述 在应用Application1中存在A.B两个activity,当在应用启动了A.B activity,点击Recent键,如何让A.B两个activity都显示在Recent界面(最近任务 ...

  10. linux开启远程访问端口

    开启3306端口的tcp访问权限 /sbin/iptables -I INPUT -p tcp -dport 3306 -j ACCEPT 保存防火墙信息 /etc/rc.d/init.d/iptab ...