springboot异步调用的介绍(附代码)

springboot异步调用的介绍(附代码),第1张

springboot异步调用的介绍(附代码)

本篇文章给大家带来的内容是关于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
控制台打印顺序:

  1. 主线程开始
  2. 打印j循环
  3. 打印i循环
  4. 主线程结束
异步代码

在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);
    }
}

再次请求打印顺序如下:

  1. 主线程开始
  2. 打印j循环
  3. 主线程结束
  4. 打印i循环

以上就是springboot异步调用的介绍(附代码)的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/687282.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-21
下一篇 2022-04-21

发表评论

登录后才能评论

评论列表(0条)

保存