这篇文章主要介绍了springboot异步调用是什么,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。
同步
程序按照定义顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执行,就是在发出一个功能调用时,在没有得到结果之前,该调用就不返回。
异步
程序在顺序执行时,不等待异步调用的语句返回结果就执行后面的程序,当一个异步过程调用发出后,调用者不能立刻得到结果。
同步代码
Service层:
public void test() throws InterruptedException {
Thread.sleep(2000);
for (int i = 0; i < 1000; i++) {
System.out.println("i = " + i);
}
}
Controller层:
@GetMapping("test")
public String test() {
try {
Thread.sleep(1000);
System.out.println("主线程开始");
for (int j = 0; j < 100; j++) {
System.out.println("j = " + j);
}
asyncService.test();
System.out.println("主线程结束");
return "async";
} catch (InterruptedException e) {
e.printStackTrace();
return "fail";
}
}
浏览器中请求 http://localhost:8080/test
控制台打印顺序:
在Service层的test方法上加上@Async
注解,同时为了是异步生效在启动类上加上@EnableAsync
注解
Service层:
@Async
public void test() throws InterruptedException {
Thread.sleep(2000);
for (int i = 0; i < 1000; i++) {
System.out.println("i = " + i);
}
}
Controller不变,启动类加上@EnableAsync
:
@SpringBootApplication
@EnableAsync
public class AsyncApplication {
public static void main(String[] args) {
SpringApplication.run(AsyncApplication.class, args);
}
}
再次请求打印顺序如下:
感谢你能够认真阅读完这篇文章,希望小编分享springboot异步调用是什么内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。