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

 更新时间:2022年02月17日 16:17:04   作者:牛奋lch  
这篇文章主要介绍了spring boot使用自定义配置的线程池执行Async异步任务,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

在前面的博客中,//www.jb51.net/article/106718.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即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • java中并发Queue种类与各自API特点以及使用场景说明

    java中并发Queue种类与各自API特点以及使用场景说明

    这篇文章主要介绍了java中并发Queue种类与各自API特点以及使用场景说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • SpringBoot的API文档生成工具SpringDoc使用详解

    SpringBoot的API文档生成工具SpringDoc使用详解

    这篇文章主要为大家介绍了SpringBoot的API文档生成工具SpringDoc使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • SpringBoot自动装配之@Enable深入讲解

    SpringBoot自动装配之@Enable深入讲解

    这篇文章主要介绍了SpringBoot自动装配之@Enable,SpringBoot中提供了很多Enable开头的注解,这些注解都是用于动态启用某些功能的。而其底层原理是使用@Import注 解导入一些配置类,实现Bean的动态加载
    2023-01-01
  • Spring Boot配置内容加密实现敏感信息保护

    Spring Boot配置内容加密实现敏感信息保护

    之前我们讲过的配置相关知识都是Spring Boot原生就提供的,而今天我们将介绍的功能并非Spring Boot原生就支持,但却非常有用:配置内容的加密
    2021-11-11
  • MyBatis的通俗理解:SqlSession.getMapper()源码解读

    MyBatis的通俗理解:SqlSession.getMapper()源码解读

    这篇文章主要介绍了MyBatis的通俗理解:SqlSession.getMapper()源码解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Mybatis实现插入数据后返回主键过程解析

    Mybatis实现插入数据后返回主键过程解析

    这篇文章主要介绍了Mybatis实现插入数据后返回主键过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • springboot扫描自定义的servlet和filter代码详解

    springboot扫描自定义的servlet和filter代码详解

    本文是一篇根据作者工作经历总结出来的关于springboot扫描自定义的servlet和filter代码详解的文章,小编觉得非常不错,这里给大家分享下,和朋友们一起学习,进步。
    2017-10-10
  • 一文学会如何在SpringBoot中使用线程池执行定时任务

    一文学会如何在SpringBoot中使用线程池执行定时任务

    在开发现代应用程序时,定时任务是一项常见的需求,SpringBoot提供了一个强大的定时任务框架,可以轻松地执行各种定时任务,结合线程池的使用,可以更好地管理任务的执行,提高系统的性能和稳定性,本文将介绍如何在Spring Boot中使用线程池执行定时任务
    2023-06-06
  • Spring boot按日切分spring boot的nohup.out日志文件的方法

    Spring boot按日切分spring boot的nohup.out日志文件的方法

    过大的日志文件维护起来存在诸多问题,所以最好是能够按日或按大小切分日志文件,下面小编给大家带来了Spring boot按日切分spring boot的nohup.out日志文件的方法,一起看看吧
    2018-08-08
  • 浅谈spring aop的五种通知类型

    浅谈spring aop的五种通知类型

    这篇文章主要介绍了浅谈spring aop的五种通知类型,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12

最新评论