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

前  言:
最近在做订单模块,用户购买服务类产品之后,需要进行预约,预约成功之后分别给商家和用户发送提醒短信。考虑发短信耗时的情况所以我想用异步的方法去执行,于是就在网上看见了Spring的@Async了。但是遇到了许多问题,使得@Async无效,也一直没有找到很好的文章去详细的说明@Async的正确及错误的使用方法及需要注意的地方,这里简单整理了一下遇见的问题,Spring是以配置文件的形式来开启@Async,而SpringBoot则是以注解的方式开启。

ps:线程池配合定时任务效果绝佳:

基于springBoot的定时任务https://blog.csdn.net/Muscleheng/article/details/106838086

我们可以使用springBoot默认的线程池,不过一般我们会自定义线程池(因为比较灵活),配置方式有:

1. 使用 xml 文件配置的方式

2. 使用Java代码结合@Configuration进行配置(推荐使用)

下面分别实现两种配置方式

第一步、配置@Async

一、springBoot启动类的配置:

在Spring Boot的主程序中配置@EnableAsync,如下所示:


   
   
  1. @ServletComponentScan
  2. @SpringBootApplication
  3. @EnableAsync // 开启@Async注解
  4. public class DemoApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(DemoApplication.class, args);
  7. }
  8. }

二、Spring XML的配置方式:

1. applicationContext.xml同目录下创建文件threadPool.xml文件:


   
   
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:task= "http://www.springframework.org/schema/task"
  5. xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
  7. <!-- 开启异步,并引入线程池 -->
  8. <task:annotation-driven executor="threadPool" />
  9. <!-- 定义线程池 -->
  10. <bean id="threadPool"
  11. class= "org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
  12. <!-- 核心线程数,默认为1 -->
  13. <property name="corePoolSize" value="10" />
  14. <!-- 最大线程数,默认为Integer.MAX_VALUE -->
  15. <property name="maxPoolSize" value="50" />
  16. <!-- 队列最大长度,一般需要设置值>=notifyScheduledMainExecutor.maxNum;默认为Integer.MAX_VALUE -->
  17. <property name="queueCapacity" value="100" />
  18. <!-- 线程池维护线程所允许的空闲时间,默认为60s -->
  19. <property name="keepAliveSeconds" value="30" />
  20. <!-- 完成任务自动关闭 , 默认为false-->
  21. <property name="waitForTasksToCompleteOnShutdown" value="true" />
  22. <!-- 核心线程超时退出,默认为false -->
  23. <property name="allowCoreThreadTimeOut" value="true" />
  24. <!-- 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者 -->
  25. <property name="rejectedExecutionHandler">
  26. <!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 -->
  27. <!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->
  28. <!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
  29. <!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
  30. <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
  31. </property>
  32. </bean>
  33. </beans>

2. 然后在applicationContext.xml中引入threadPool.xml:<import resource="threadPool.xml" />


   
   
  1. <!--如果不使用自定义线程池,可以直接使用下面这段标签-->
  2. <!--
  3. <task:executor id="WhifExecutor" pool-size="10"/>
  4. -->
  5. <import resource="threadPool.xml" />
  6. <task:annotation-driven executor="WhifExecutor" />

第二步:创建两个异步方法的类,如下所示:

第一个类(这里模拟取消订单后发短信,有两个发送短信的方法):


   
   
  1. @Service
  2. public class TranTest2Service {
  3. // 发送提醒短信 1
  4. @Async
  5. public void sendMessage1() throws InterruptedException {
  6. System.out.println( "发送短信方法---- 1 执行开始");
  7. Thread.sleep( 5000); // 模拟耗时
  8. System.out.println( "发送短信方法---- 1 执行结束");
  9. }
  10. // 发送提醒短信 2
  11. @Async
  12. public void sendMessage2() throws InterruptedException {
  13. System.out.println( "发送短信方法---- 2 执行开始");
  14. Thread.sleep( 2000); // 模拟耗时
  15. System.out.println( "发送短信方法---- 2 执行结束");
  16. }
  17. }

第二个类。调用发短信的方法 (异步方法不能与被调用的异步方法在同一个类中,否则无效):


   
   
  1. @Service
  2. public class OrderTaskServic {
  3. @Autowired
  4. private TranTest2Service tranTest2Service;
  5. // 订单处理任务
  6. public void orderTask() throws InterruptedException {
  7. this.cancelOrder(); // 取消订单
  8. tranTest2Service.sendMessage1(); // 发短信的方法 1
  9. tranTest2Service.sendMessage2(); // 发短信的方法 2
  10. }
  11. // 取消订单
  12. public void cancelOrder() throws InterruptedException {
  13. System.out.println( "取消订单的方法执行------开始");
  14. System.out.println( "取消订单的方法执行------结束 ");
  15. }
  16. }

经过测试得到如下结果:

1. 没有使用@Async

2. 使用了@Async

可以看出,没有使用@Async方式实现的发送短信是同步执行的,意思就是说第一条发送之后再发送第二条,第二条发送成功之后再给用户提示,这样显然会影响用户体验,再看使用了@Async实现的,在执行第一个发送短信方法之后马上开启另一个线程执行第二个方法,显然这样我们的处理速度回快很多。

使用Java代码结合@Configuration注解的配置方式(推荐使用)

1. 新建一个配置类


   
   
  1. package com.boot.common.conf;
  2. import java.util.concurrent.ThreadPoolExecutor;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.scheduling.annotation.EnableAsync;
  6. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  7. /**
  8. * 线程池配置
  9. * @author zhh
  10. *
  11. */
  12. @Configuration
  13. @EnableAsync
  14. public class ThreadPoolTaskConfig {
  15. /**
  16. * 默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,
  17. * 当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
  18. * 当队列满了,就继续创建线程,当线程数量大于等于maxPoolSize后,开始使用拒绝策略拒绝
  19. */
  20. /** 核心线程数(默认线程数) */
  21. private static final int corePoolSize = 20;
  22. /** 最大线程数 */
  23. private static final int maxPoolSize = 100;
  24. /** 允许线程空闲时间(单位:默认为秒) */
  25. private static final int keepAliveTime = 10;
  26. /** 缓冲队列大小 */
  27. private static final int queueCapacity = 200;
  28. /** 线程池名前缀 */
  29. private static final String threadNamePrefix = "Async-Service-";
  30. @Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
  31. public ThreadPoolTaskExecutor taskExecutor(){
  32. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  33. executor.setCorePoolSize(corePoolSize);
  34. executor.setMaxPoolSize(maxPoolSize);
  35. executor.setQueueCapacity(queueCapacity);
  36. executor.setKeepAliveSeconds(keepAliveTime);
  37. executor.setThreadNamePrefix(threadNamePrefix);
  38. // 线程池对拒绝任务的处理策略
  39. // CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务
  40. executor.setRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy());
  41. // 初始化
  42. executor.initialize();
  43. return executor;
  44. }
  45. }

2:创建两个异步方法的类(和之前的类类似仅仅是方法上注解不一样),如下所示:

第一个类(这里模拟取消订单后发短信,有两个发送短信的方法):


   
   
  1. package com.boot.test1.service;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.scheduling.annotation.Async;
  5. import org.springframework.stereotype.Service;
  6. @Service
  7. public class TranTest2Service {
  8. Logger log = LoggerFactory.getLogger(TranTest2Service.class);
  9. // 发送提醒短信 1
  10. @Async("taskExecutor") // 指定线程池,也可以直接写@Async
  11. public void sendMessage1() throws InterruptedException {
  12. log.info( "发送短信方法---- 1 执行开始");
  13. Thread.sleep( 5000); // 模拟耗时
  14. log.info( "发送短信方法---- 1 执行结束");
  15. }
  16. // 发送提醒短信 2
  17. @Async("taskExecutor") // 指定线程池,也可以直接写@Async
  18. public void sendMessage2() throws InterruptedException {
  19. log.info( "发送短信方法---- 2 执行开始");
  20. Thread.sleep( 2000); // 模拟耗时
  21. log.info( "发送短信方法---- 2 执行结束");
  22. }
  23. }

代码中的 @Async("taskExecutor") 对应我们自定义线程池中的 @Bean("taskExecutor") ,表示使用我们自定义的线程池。也可以直接写@Async

第二个类。调用发短信的方法 (异步方法不能与被调用的异步方法在同一个类中,否则无效):


   
   
  1. @Service
  2. public class OrderTaskServic {
  3. @Autowired
  4. private TranTest2Service tranTest2Service;
  5. // 订单处理任务
  6. public void orderTask() throws InterruptedException {
  7. this.cancelOrder(); // 取消订单
  8. tranTest2Service.sendMessage1(); // 发短信的方法 1
  9. tranTest2Service.sendMessage2(); // 发短信的方法 2
  10. }
  11. // 取消订单
  12. public void cancelOrder() throws InterruptedException {
  13. System.out.println( "取消订单的方法执行------开始");
  14. System.out.println( "取消订单的方法执行------结束 ");
  15. }
  16. }

运行截图:

注意看,截图中的 [nio-8090-exec-1] 是Tomcat的线程名称

 [Async-Service-1]、[Async-Service-2]表示线程1和线程2 ,是我们自定义的线程池里面的线程名称,我们在配置类里面定义的线程池前缀:

private static final String threadNamePrefix = "Async-Service-"; // 线程池名前缀,说明我们自定义的线程池被使用了。

注意事项:

如下方式会使@Async失效


一、异步方法使用static修饰
二、异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类
三、异步方法不能与被调用的异步方法在同一个类中
四、类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
五、如果使用SpringBoot框架必须在启动类中增加@EnableAsync注解

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值