本文来自于千锋教育在阿里云开发者社区学习中心上线课程《SpringBoot实战教程》,主讲人杨红艳,点击查看视频内容。
21.异步调用:
在项目中,当访问其它接口较慢或者做耗时任务时,不想程序一直卡在耗时任务上,想程序能够并行执行,我们可以使用多线程来并行的处理任务,SpringBoot提供了异步处理方式@Async。
编写AsyncService:
public interface AsyncService {
Future doTask1()throws Exception;
Future doTask2()throws Exception;
Future doTask3()throws Exception;
}
编写AsyncServiceImpl:
@Service
public class AsyncServiceImpl implements AsyncService {
public static Random random =new Random();
@Async
@Override
public Future doTask1() throws Exception {
System.out.println("开始做任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("任务一完成");
}
@Async
@Override
public Future doTask2()throws Exception {
System.out.println("开始做任务二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("任务二完成");
}
@Async
@Override
public Future doTask3() throws Exception{
System.out.println("开始做任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("任务三完成");
}
}
在Controller中调用service功能:
@Controller
public class TestController {
@Autowired
private AsyncService asyncService;
@RequestMapping("/async")
@ResponseBody
public String getEntityById() throws Exception {
long start = System.currentTimeMillis();
Future task1 = asyncService.doTask1();
Future task2 = asyncService.doTask2();
Future task3 = asyncService.doTask3();
while(true) {
if(task1.isDone() && task2.isDone() && task3.isDone()) {
// 三个任务都调用完成,退出循环等待
break;
}
Thread.sleep(1000);
}
long end = System.currentTimeMillis();
return "任务全部完成,总耗时:" + (end - start) + "毫秒";
}
}
要是使用异步的话,还需启动类中开始异步执行。
在启动类上加入@EnableAsync注解。
执行的结果为: