spring boot使用自定义的线程池执行Async任务
作者:牛奋lch 发布时间:2023-08-15 07:41:25
在前面的博客中,https://www.jb51.net/article/134866.htm 我们使用了spring boot的异步操作,当时,我们使用的是默认的线程池,但是,如果我们想根据项目来定制自己的线程池了,下面就来说说,如何定制线程池!
一、增加配置属性类
package com.chhliu.springboot.async.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "spring.task.pool") // 该注解的locations已经被启用,现在只要是在环境中,都会优先加载
public class TaskThreadPoolConfig {
private int corePoolSize;
private int maxPoolSize;
private int keepAliveSeconds;
private int queueCapacity;
…………省略getter,setter方法…………
}
二、创建线程池
package com.chhliu.springboot.async.pool;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.beans.factory.annotation.Autowired;
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 com.chhliu.springboot.async.configuration.TaskThreadPoolConfig;
@Configuration
@EnableAsync
public class TaskExecutePool {
@Autowired
private TaskThreadPoolConfig config;
@Bean
public Executor myTaskAsyncPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.getCorePoolSize());
executor.setMaxPoolSize(config.getMaxPoolSize());
executor.setQueueCapacity(config.getQueueCapacity());
executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
executor.setThreadNamePrefix("MyExecutor-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
三、在主类中开启配置支持
package com.chhliu.springboot.async;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableAsync;
import com.chhliu.springboot.async.configuration.TaskThreadPoolConfig;
@SpringBootApplication
@EnableAsync
@EnableConfigurationProperties({TaskThreadPoolConfig.class} ) // 开启配置属性支持
public class SpringbootAsyncApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAsyncApplication.class, args);
}
}
四、测试类
package com.chhliu.springboot.async.pool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncTask {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Async("myTaskAsyncPool") //myTaskAsynPool即配置线程池的方法名,此处如果不写自定义线程池的方法名,会使用默认的线程池
public void doTask1(int i) throws InterruptedException{
logger.info("Task"+i+" started.");
}
}
五、测试
package com.chhliu.springboot.async;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.chhliu.springboot.async.pool.AsyncTask;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootAsyncApplicationTests {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private AsyncTask asyncTask;
@Test
public void AsyncTaskTest() throws InterruptedException, ExecutionException {
for (int i = 0; i < 100; i++) {
asyncTask.doTask1(i);
}
logger.info("All tasks finished.");
}
}
测试结果如下:
2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-10] c.c.springboot.async.pool.AsyncTask : Task60 started.
2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-25] c.c.springboot.async.pool.AsyncTask : Task61 started.
2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-6] c.c.springboot.async.pool.AsyncTask : Task62 started.
2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-23] c.c.springboot.async.pool.AsyncTask : Task63 started.
2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-20] c.c.springboot.async.pool.AsyncTask : Task64 started.
2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-19] c.c.springboot.async.pool.AsyncTask : Task65 started.
2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-16] c.c.springboot.async.pool.AsyncTask : Task66 started.
2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-15] c.c.springboot.async.pool.AsyncTask : Task67 started.
2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-12] c.c.springboot.async.pool.AsyncTask : Task68 started.
2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-1] c.c.springboot.async.pool.AsyncTask : Task69 started.
2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-11] c.c.springboot.async.pool.AsyncTask : Task81 started.
2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-8] c.c.springboot.async.pool.AsyncTask : Task82 started.
2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-7] c.c.springboot.async.pool.AsyncTask : Task83 started.
2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-4] c.c.springboot.async.pool.AsyncTask : Task84 started.
2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-29] c.c.springboot.async.pool.AsyncTask : Task85 started.
2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-21] c.c.springboot.async.pool.AsyncTask : Task86 started.
2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-17] c.c.springboot.async.pool.AsyncTask : Task88 started.
测试结果ok!
六、配置默认的线程池
如果我们想使用默认的线程池,但是只是想修改默认线程池的配置,那怎么做了,此时我们需要实现AsyncConfigurer类,示例代码如下:
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import com.chhliu.cq.emailservice.threadconfiguration.TaskThreadPoolConfig;
import lombok.extern.slf4j.Slf4j;
/**
* 注意:该线程池被所有的异步任务共享,而不属于某一个异步任务
* 描述:配置异步任务的线程池
* @author chhliu
* 创建时间:2017年5月22日 上午10:20:56
* @version 1.2.0
*/
@Slf4j
@Configuration
public class AsyncTaskExecutePool implements AsyncConfigurer{
@Autowired
private TaskThreadPoolConfig config; // 配置属性类,见上面的代码
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.getCorePoolSize());
executor.setMaxPoolSize(config.getMaxPoolSize());
executor.setQueueCapacity(config.getQueueCapacity());
executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
executor.setThreadNamePrefix("taskExecutor-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {// 异步任务中异常处理
return new AsyncUncaughtExceptionHandler() {
@Override
public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) {
log.error("=========================="+arg0.getMessage()+"=======================", arg0);
log.error("exception method:"+arg1.getName());
}
};
}
}
使用的时候,只需在方法上加上@Async即可。
总结
以上所述是小编给大家介绍的spring boot使用自定义的线程池执行Async任务网站的支持!
来源:http://blog.csdn.net/liuchuanhong1/article/details/64132520
猜你喜欢
- 鼠标事件的事件源往往与容器相关,当鼠标进入容器、离开容器,或者在容器中单击鼠标、拖动鼠标时都会发生鼠标事件。java语言为处理鼠标事件提供两
- 限流器算法目前常用限流器算法为两种:令牌桶算法和漏桶算法,主要区别在于:漏桶算法能够强行限制请求速率,平滑突发请求,而令牌桶算法在限定平均速
- 先随便创建一个存储过程DELIMITER $$CREATE PROCEDUREgetUserNameById (IN i_id BIGINT
- 实现跨服务的远程调用(RestTemplate)业务场景:在返回订单信息数据中显示用户信息实现思路:基于RestTemplate发起的htt
- 此例子,用于说明如何在Java中对“注解 Annotation”的定义、使用和解析的操作。注解一般用于自定义开发框架中,至于为什么使用,此处
- 1.前言(基于JDK1.7)最近想把一些java基础的东西整理一下,但是又不知道从哪里开始!想了好久,还是从最基本的jvm开始吧!这一节就简
- 先来看问题纠结了几个小时终于找到了问题所在,因为shiro的realm属于Filter,简单说就是初始化realm时,spring还未加载相
- 微信公众号发送模版消息 背景:如下图,当用户发布需求的时候,公众号自定推送消息。例如:微信支付的时候,公众号会推送支付成功消息前提:发送模版
- 一.mybatis的配置1.1 添加相应的jar包在lib文件夹下面添加mybatis的核心jar包以及依赖的jar包同在lib文件夹下面加
- java 中HashCode重复的可能性今天有同事提议用String的hashcode得到int类型作为主键。其实hashcode重复的可能
- 目录1、IP地址2、端口3、通信协议3.1 TCP/IP协议簇:实际上是一组协议3.2 TCP UDP对比3.3 TCP实现聊天3.4 TC
- 1.场景线程池使用DiscardOldestPolicy拒绝策略,阻塞队列使用ArrayBlockingQueue,发现在某些情形下对于得到
- 事件函数的执行顺序先说一下执行顺序吧。 官方给出的脚本中事件函数的执行顺序如下图: 我们可以做一个小实验来测试一下: 在Hierarchy
- 当我们拿到一大段JSON字符串的时候,分析起来简直头皮发麻,相信很大一部分朋友也都会直接去BEJSON等网站去做一个JSON格式化,已方便自
- 二维数组遍历:思想:1.先将二维数组中所有的元素拿到2.再将二维数组中每个元素进行遍历,相当于就是在遍历一个一维数组第一种方法:双重for循
- 介绍在本文中,我们将了解如何将现有应用程序迁移到Spring 6以及如何充分利用此升级。本文中的提示基于我在Hypersistence Op
- 本文实例讲述了C#从命令行读取参数的方法。分享给大家供大家参考。具体如下:using System;class MainClass{ pub
- 国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式。它要求从产品中抽离所有地域语言,国家/地
- 1. 什么是静态内部类在Java中有静态代码块、静态变量、静态方法,当然也有静态类,但Java中的静态类只能是Java的内部类,也称为静态嵌
- 介绍我们都知道函数是程序中的基本模块,代码段。那高阶函数呢?听起来很好理解吧,就是函数的高阶(级)版本。它怎么高阶了呢?我们来看下它的基本定