spring boot 学习(十一)使用@Async实现异步调用

时间:2022-12-10 11:11:43

使用@Async实现异步调用

什么是”异步调用”与”同步调用”

“同步调用”就是程序按照一定的顺序依次执行,,每一行程序代码必须等上一行代码执行完毕才能执行;”异步调用”则是只要上一行代码执行,无需等待结果的返回就开始执行本身任务。
通常情况下,”同步调用”执行程序所花费的时间比较多,执行效率比较差。所以,在代码本身不存在依赖关系的话,我们可以考虑通过”异步调用”的方式来并发执行。

“异步调用”

在 spring boot 框架中,只要提过@Async注解就能奖普通的同步任务改为异步调用任务。
注意: @Async所修饰的函数不要定义为static类型,这样异步调用不会生效

1. 开启@Async注解

在Spring Boot主类添加@EnableAsync注解

2. 定义异步任务

定义Task类,创建三个处理函数分别模拟三个执行任务的操作,操作消耗时间随机取(10秒内)。

@Component
public class Task { //定义一个随机对象.
public static Random random =new Random(); @Async //加入"异步调用"注解
public void doTaskOne() throws InterruptedException {
System.out.println("开始执行任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
} @Async
public void doTaskTwo() throws InterruptedException {
System.out.println("开始执行任务二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
} @Async
public void doTaaskThree() throws InterruptedException {
System.out.println("开始执行任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
}
}
3. 创建Controller进行测试

注意@Autowired注入类,因为这个类已经被 Spring 管理了。如果使用 new 来获得线程类将不会执行异步效果,这里涉及到在 Spring 中使用多线程。

@Controller
public class TaskController { @Autowired
private Task TASK; @ResponseBody
@RequestMapping("/task")
public String task() throws Exception {
System.out.println("开始执行Controller任务");
long start = System.currentTimeMillis();
TASK.doTaskOne();
TASK.doTaskTwo();
TASK.doTaaskThree();
long end = System.currentTimeMillis();
System.out.println("完成Controller任务,耗时:" + (end - start) + "毫秒");
return "success";
}
}

4. 多次调用

访问 http://localhost:8080/task 截图:
spring boot 学习(十一)使用@Async实现异步调用