0
点赞
收藏
分享

微信扫一扫

SpringBoot异步任务


SpringBoot异步任务

  • ​​一、序言​​
  • ​​二、测试步骤​​
  • ​​1、创建AsyncService​​
  • ​​2、创建AsyncController​​
  • ​​3、不使用异步注解时运行测试:​​
  • ​​4、使用异步注解​​
  • ​​5、测试​​

一、序言

在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。

二、测试步骤

1、创建AsyncService

这里先不加​​@Async​​注解,并让线程休眠3秒

package com.atguigu.springboot.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
//告诉spring,这是一个异步方法
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据中...");
}
}

2、创建AsyncController

package com.atguigu.springboot.controller;

import com.atguigu.springboot.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;

@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "success";
}
}

3、不使用异步注解时运行测试:

结果:访问​​http://localhost:8080/hello​​时,回卡一会才能出现success

4、使用异步注解

在AsyncService的方法里加上​​@Async​​​注解
在启动类上面加上​​​@EnableAsync​​注解开启注解功能

5、测试

使用了异步注解之后,页面直接显示success,控制台隔了3秒也正常输出处理数据中,说明确实是异步执行的

SpringBoot异步任务_spring


SpringBoot异步任务_spring boot_02


举报

相关推荐

0 条评论