springboot中使用@Async实现异步方法调用

ゝ一世哀愁。 2023-09-24 22:54 86阅读 0赞

1、场景描述

我们在开发的过程中,可能会遇见如下场景:

一个业务A,这个A业务中包含了4个小业务,分别是a,b,c,d。在实际操作中,有时候第三个业务c,执行的时间比较长或者c业务是属于其他系统的api调用。这个时候,我们就期望a,c,d三个也是先执行完毕,然后提示用户业务成功。而不必等待c业务结束后,在提示用户。这样的好处是,能够实现业务分离,且用户体验较好。

常见的应用场景:如短信方法,订单提交,邮件发送,消息推送等。

常见的解决办法:

第一种:可以通过RabbitMQ\ActiveMQ\KAFKA等消息中间件实现

第二种:可以通过@Async注解实现

总结:

如果调用的服务涉及到其他系统建议使用消息中间件

如果调用的服务都在一个工程中,建议使用@Async注解,足够使用。

2、@Async实现异步调用方式

2.1、创建sprigboot工程

我使用的springboot是2.7.9版本,同时选择了springboot-web开发,包信息如下

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.7.9</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-web</artifactId>
  10. </dependency>

2.2、在启动类中开启异步任务

  1. @EnableAsync//开启异步任务
  2. @SpringBootApplication
  3. public class SpringbootAsyncApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(SpringbootAsyncApplication.class, args);
  6. }
  7. }

2.3、创建StudentAsyncService业务类

说明1:@Async注解写在类上,表示所有方法都异步执行,写在方法上表示某一个方法异步执行

说明2:StudentAsyncService需要被spring扫描到,如果是业务层使用@Service,其他地方使用@Component注解。

  1. @Service
  2. public class StudentAsyncService {
  3. @Async//那个方法需要使用异步调用,就使用该注解
  4. public void asyncMethod(String data) {
  5. try{
  6. Thread.sleep(6000);//模拟异步执行业务的时间
  7. }catch (Exception e){
  8. System.out.println(e.getStackTrace());
  9. }
  10. System.out.println("=======异步线程执行结束========");
  11. }
  12. }

2.4、创建控制层类调用service异步方法

  1. @Controller
  2. public class StudentController {
  3. @Autowired
  4. private StudentAsyncService studentAsyncService;
  5. @RequestMapping("/testMethod")
  6. public String testMethod(){
  7. System.out.println("======主线程开始执行======");
  8. studentAsyncService.asyncMethod("你要传递的数据");//异步执行方法
  9. System.out.println("======主线程结束执行======");
  10. return "index";//返回的视图逻辑地址
  11. }
  12. }

2.5、测试结果

访问地址:http://localhost:8080/testMethod

87181456fb3248068d977da5f0684305.png

通过结果我们可以看出,主线程任务有限执行结束,6秒后异步代码执行结束。

发表评论

表情:
评论列表 (有 0 条评论,86人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot使用@Async异步调用方法

    1、业务场景,在使用阿里大鱼发送短信时,不知因何原因,后端接口发送短信较耗时,前端请求后端接口很快出现请求错误,这跟前端设置的响应时间相关,可以让前端增加时间,但这并不是一个好