springboot 异步接口的实现方法

程序在顺序执行时,不等待异步调用的语句返回结果就执行后面的程序,当一个异步过程调用发出后,调用者无需等待异步任务的结果即可继续执行主进程的代码。

controller层

    @Autowired
    private AsyncService asyncService;

    @GetMapping("syncData")
    public String test() {
        try {
            Thread.sleep(1000);
            System.out.println("主线程开始");
            for (int j = 0; j < 10; j++) {
                System.out.println("j = " + j);
            }
            asyncService.syncData();
            System.out.println("主线程结束");
            return "async";
        } catch (InterruptedException e) {
            e.printStackTrace();
            return "fail";
        }
    }

service层,需要在service层异步方法上添加  @Async 注解,同时要在启动类加上@EnableAsync 注解 启动异步功能

    @Async
    public void syncData() throws InterruptedException {
        Thread.sleep(5000);
        for (int i = 0; i < 10; i++) {
            System.out.println("i = " + i);
        }
    }

启动项目后,调用接口,当主进程结束后,页面已经拿到接口的返回结果,经过设置的 sleep 时间(5秒)后,异步任务执行完成

            

猜你喜欢

转载自blog.csdn.net/qq_43039260/article/details/116603917