![8ce68f6adc4e7a821cb48ea8b076ed6d.png](https://img-blog.csdnimg.cn/img_convert/8ce68f6adc4e7a821cb48ea8b076ed6d.png)
作者:Muscleheng http:// blog.csdn.net/Musclehen g/article/details/81409672
前言
最近在做订单模块,用户购买服务类产品之后,需要进行预约,预约成功之后分别给商家和用户发送提醒短信。考虑发短信耗时的情况所以我想用异步的方法去执行,于是就在网上看见了Spring的@Async了。
但是遇到了许多问题,使得@Async无效,也一直没有找到很好的文章去详细的说明@Async的正确及错误的使用方法及需要注意的地方,这里简单整理了一下遇见的问题,Sring是以配置文件的形式来开启@Async,而SpringBoot则是以注解的方式开启。
我们可以使用springBoot默认的线程池,不过一般我们会自定义线程池(因为比较灵活),配置方式有:
- 使用 xml 文件配置的方式
- 使用Java代码结合@Configuration进行配置(推荐使用)
下面分别实现两种配置方式
第一步、配置@Async
一、springBoot启动类的配置:
在Spring Boot的主程序中配置@EnableAsync,如下所示:
@ServletComponentScan
@SpringBootApplication
@EnableAsync
public class ClubApiApplication {
public static void main(String[] args) {
SpringApplication.run(ClubApiApplication.class, args);
}
}
二、Spring XML的配置方式:
1.applicationContext.xml同目录下创建文件threadPool.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<!-- 开启异步,并引入线程池 -->
<task:annotation-driven executor="threadPool" />
<!-- 定义线程池 -->
<bean id="threadPool"
class="org.springframework.scheduling.concu