1.串行接口示例 controller层
/**
* @Description:方法描述
* @Param: 串行接口
* @return:
* @date: 2022/11/3
* @version 1.0
*/
@GetMapping("/testTask")
public Map<Object, Object> testTask() throws Exception {
HashMap<Object, Object> map = new HashMap<>();
long l = System.currentTimeMillis();
String s1 = testTaskService.testTask1();
map.put("s1", s1);
String s2 = testTaskService.testTask2();
map.put("s2", s2);
String s3 = testTaskService.testTask3();
map.put("s3", s3);
long l1 = System.currentTimeMillis();
System.out.println("串行接口用时:" + (l1 - l) / 1000 + "秒");
return map;
}
2.并行接口示例 controller层
/**
* @Description:方法描述
* @Param:
* @return:并行接口优化
* @date: 2022/11/3
* @version 1.0
*/
@GetMapping("/testTask2")
public Map<Object, Object> testTask2() throws Exception {
HashMap<Object, Object> map = new HashMap<>();
long l = System.currentTimeMillis();
// supplyAsync runAsync
CompletableFuture.allOf(
CompletableFuture.runAsync(() -> {
map.put("s1", testTaskService.testTask1());
}, ForkJoinPool.commonPool()),
CompletableFuture.runAsync(() -> {
map.put("s2", testTaskService.testTask2());
}, ForkJoinPool.commonPool()),
CompletableFuture.runAsync(() -> {
map.put("s3", testTaskService.testTask3());
}, ForkJoinPool.commonPool())
).join();
long l1 = System.currentTimeMillis();
System.out.println("并行接口用时:" + (l1 - l) / 1000 + "秒");
return map;
}
模拟接口查询接口速度
@Service
public class TestTaskService {
public String testTask1() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "testTask1";
}
public String testTask2() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "testTask2";
}
public String testTask3() {
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "testTask5";
}
}
执行结果:
串行接口用时:9秒 正好是每个接口所花费的时间总和(2+2+5)
并行接口用时:5秒 是几个接口中花费时间最长的一个时间点 5
串行接口改并行接口,接口查询速度快了好多!