什么是”异步调用”与”同步调用”
“同步调用”就是程序按照一定的顺序依次执行,,每一行程序代码必须等上一行代码执行完毕才能执行;”异步调用”则是只要上一行代码执行,无需等待结果的返回就开始执行本身任务。
通常情况下,”同步调用”执行程序所花费的时间比较多,执行效率比较差。所以,在代码本身不存在依赖关系的话,我们可以考虑通过”异步调用”的方式来并发执行。
下面通过两个简单的案例向大家介绍一个同步调用与异步调用的不同,编写下代码时必须先创建一个Maven项目,并引入spring-boot-starter-web,SpringBoot版本为1.5.9.
同步调用
定义Task类,创建三个处理函数分别模拟三个执行任务的操作
package org.lvgang;
import org.springframework.stereotype.Component;
@Component
public class Task {
public void task1() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(1000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
public void task2() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(2000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
public void task3() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(3000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
}
创建Controller进行测试
package org.lvgang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("task")
public class TaskController {
@Autowired Task task;
@RequestMapping("")
public String doTask() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
task.task1();
task.task2();
task.task3();
long currentTimeMillis1 = System.currentTimeMillis();
return "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
}
}
创建SpringBoot启动类
package org.lvgang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* SpringBoot Main
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
运行结果
启动项目之后,在浏览器中访问以下联接:http://localhost:8080/task
控制台输出
task1任务耗时:1000ms
task2任务耗时:2001ms
task3任务耗时:3000ms
浏览器输出
task任务总耗时:6001ms
通过输入的信息可以看出task1,task2,task3是顺序的执行完了
异步调用
定义Task类,创建三个处理函数分别模拟三个执行任务的操作
package org.lvgang;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncTask {
@Async
public void task1() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(1000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
@Async
public void task2() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(2000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
@Async
public void task3() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(3000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
}
在Spring Boot中,我们只需要通过使用@Async注解就能简单的将原来的同步函数变为异步函数
注: @Async所修饰的函数不要定义为static类型,这样异步调用不会生效
创建Controller进行测试
package org.lvgang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("asynctask")
public class AsyncTaskController {
@Autowired AsyncTask asyncTask;
@RequestMapping("")
public String doTask() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
asyncTask.task1();
asyncTask.task2();
asyncTask.task3();
long currentTimeMillis1 = System.currentTimeMillis();
return "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
}
}
创建SpringBoot启动类
package org.lvgang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* SpringBoot Main
*/
@SpringBootApplication
@EnableAsync
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsync
运行结果
启动项目之后,在浏览器中访问以下联接:http://localhost:8080/asynctask
控制台输出
task1任务耗时:1000ms
task2任务耗时:2001ms
task3任务耗时:3005ms
浏览器输出
task任务总耗时:4ms
原因是目前task1,task2,task3三个函数的时候已经是异步执行了。主程序在异步调用之后,主程序并不会理会这三个函数是否执行完成了,由于没有其他需要执行的内容,所以程序就自动结束了,导致了不完整或是没有输出任务相关内容的情况。
此时可以反复执行单元测试,您可能会遇到各种不同的结果,比如:
- 没有任何任务相关的输出
- 有部分任务相关的输出
- 乱序的任务相关的输出
异步回调
为了让task1,task2,task3能正常结束,假设我们需要统计一下三个任务并发执行共耗时多少,这就需要等到上述三个函数都完成调动之后记录时间,并计算结果。
那么我们如何判断上述三个异步调用是否已经执行完成呢?我们需要使用Future<T>来返回异步调用的结果,就像如下方式改造task1,task2,task3函数:
package org.lvgang;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;
@Component
public class FutureAsyncTask {
@Async
public Future<String> task1() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(1000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
return new AsyncResult<String>("task1任务完成");
}
@Async
public Future<String> task2() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(2000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
return new AsyncResult<String>("task2任务完成");
}
@Async
public Future<String> task3() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(3000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
return new AsyncResult<String>("task3任务完成");
}
}
创建Controller进行测试
package org.lvgang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.Future;
@RestController
@RequestMapping("futureasynctask")
public class FutureAsyncTaskController {
@Autowired FutureAsyncTask futureAsyncTask;
@RequestMapping("")
public String doTask() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Future<String> task1 = futureAsyncTask.task1();
Future<String> task2 = futureAsyncTask.task2();
Future<String> task3 = futureAsyncTask.task3();
while(true) {
if(task1.isDone() && task2.isDone() && task3.isDone()) {
// 三个任务都调用完成,退出循环等待
break;
}
Thread.sleep(1000);
}
long currentTimeMillis1 = System.currentTimeMillis();
return "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
}
}
运行结果
启动项目之后,在浏览器中访问以下联接:http://localhost:8080/futureasynctask
控制台输出
task1任务耗时:1000ms
task2任务耗时:2000ms
task2任务耗时:3000ms
浏览器输出
task任务总耗时:4003ms
可以看到,通过异步调用,让任务一、二、三并发执行,有效的减少了程序的总运行时间,并完可以看到三个任务都已经完成,并返回了结果。