在日常开发中,我们有时会遇到在调用一次接口后,其后台的业务逻辑比较复杂,需要处理多个阶段,这个时候如果使用同步串行的方式,也就是单线程的方式来执行的话,前端需要等待较长时间,也可能会出现请求超时,这个时候,如果任务的下一个阶段不依赖上一个阶段的结果我们就可以使用异步的方式来并行执行此任务以提高响应效率
示例
1、@EnableAsync
在异步方法对应的类上加上@EnableAsync注解以开启异步调用方式
@Component
@EnableAsync
public class CommonTestServiceImpl implements CommonTestService {
...
}
也可以加在启动类上,这样别的类中也有异步方法时就不
@SpringBootApplication
@EnableCaching
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2、定义相关测试类
业务接口及实现类
public interface CommonTestService {
/**
* 异步方法测试
*/
void asyncTest(List<Integer> ids);
/**
* 同步测试,对比异步结果
*/
void syncTest(List<Integer> ids);
}
@Component
@EnableAsync
public class CommonTestServiceImpl implements CommonTestService {
@Async
@Override
public void asyncTest(List<Integer> ids) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
ids.add(3);
}
@Override
public void syncTest(List<Integer> ids) {
ids.add(3);
}
}
rest接口类
@RestController
@RequestMapping("/test")
public class CommonTestController {
@Autowired
private CommonTestService commonTestService;
@GetMapping("/async")
public List<Integer> asyncRequest() {
List<Integer> ids = new ArrayList<>();
ids.add(1);
commonTestService.asyncTest(ids);
ids.add(2);
try {
Thread.sleep(1000); // 睡会,以保证返回前台时异步方法中的3已入列
} catch (InterruptedException e) {
e.printStackTrace();
}
return ids;
}
@GetMapping("/sync")
public List<Integer> syncRequest() {
List<Integer> ids = new ArrayList<>();
ids.add(1);
commonTestService.syncTest(ids);
ids.add(2);
return ids;
}
}
3、测试结果
调用同步接口名,我们可以看到值时一个个按照代码顺序串行入列的
而调用异步接口,2比3先入列,其实和多线程一个效果,主线程先执行的,而子线程后执行