spring boot使用自定义的线程池执行Async任务

 更新时间:2018年02月10日 10:03:07   作者:牛奋lch  
这篇文章主要介绍了spring boot使用自定义的线程池执行Async任务的相关资料,需要的朋友可以参考下

在前面的博客中,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任务,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

  • java实现拼图游戏

    java实现拼图游戏

    这篇文章主要为大家详细介绍了java实现拼图游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-12-12
  • 详解Java面向对象中的继承

    详解Java面向对象中的继承

    这篇文章主要介绍了详解Java面向对象中的继承,继承提高代码的复用性:通过继承,子类可以直接使用父类的属性和方法,不需要重复定义,需要的朋友可以参考下
    2023-05-05
  • Java多线程之搞定最后一公里详解

    Java多线程之搞定最后一公里详解

    Java 给多线程编程提供了内置的支持。 一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务,多线程是多任务的一种特别的形式,但多线程使用了更小的资源开销
    2021-10-10
  • Spring如何消除代码中的if-else/switch-case

    Spring如何消除代码中的if-else/switch-case

    这篇文章主要给大家介绍了关于Spring如何消除代码中if-else/switch-case的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Spring具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-04-04
  • Java正则表达式之Pattern类实例详解

    Java正则表达式之Pattern类实例详解

    Pattern类的作用在于编译正则表达式后创建一个匹配模式,下面这篇文章主要给大家介绍了关于Java正则表达式之Pattern类的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-01-01
  • 详解如何在SpringBoot中优雅地重试调用第三方API

    详解如何在SpringBoot中优雅地重试调用第三方API

    作为后端程序员,我们的日常工作就是调用一些第三方服务,将数据存入数据库,返回信息给前端。本文为大家介绍了如何在SpringBoot中优雅地重试调用第三方API,需要的可以参考一下
    2022-12-12
  • Spring中@Configuration注解的使用场景

    Spring中@Configuration注解的使用场景

    这篇文章主要介绍了Spring中@Configuration注解的使用场景,@Configuration注解是从Spring 3.0版本开始加入的一个使Spring能够支持注解驱动开发的标注型注解,主要用于标注在类上,需要的朋友可以参考下
    2023-11-11
  • Java 反射获取类详细信息的常用方法总结

    Java 反射获取类详细信息的常用方法总结

    Java 反射获取类详细信息的常用方法总结,需要的朋友可以参考一下
    2013-03-03
  • Java hutool List集合对象拷贝示例代码

    Java hutool List集合对象拷贝示例代码

    这篇文章主要介绍了Java hutool List集合对象拷贝的相关资料,文章还分享了在实现过程中遇到的一些问题,并强调了阅读源码和正确配置CopyOptions的重要性,需要的朋友可以参考下
    2024-12-12
  • Java 不同版本的 Switch语句

    Java 不同版本的 Switch语句

    本文主要介绍了Java不同版本的Switch语句,自Java13以来,Switch表达式就被添加到Java核心库中,下面我们将介绍旧的Java Switch语句和新的Switch语句的区别,需要的朋友可以参考一下
    2022-06-06

最新评论