SpringBoot 如何实现异步执行

现有这样一个场景,客户端发起请求,服务端接收到请求,并作出反馈,并且在反馈的同时需要做下日志记录

正常情况下 在这个逻辑中 发起请求 接收请求 处理业务 记录日志 返回结果,从中得知 记录日志 不属于业务范围内 ,

可将其做异步操作,这样在处理完业务直接返回结果 无需等待日志操作完成后再返回结果。

1、定义异步操作的bean

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class AnyService {

    @Async
    public String sys(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("sys  -------------------");
        return "";
    }
}

2、主程序类开启异步请求配置

@SpringBootApplication
@EnableAsync
public class UserInterfaceApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserInterfaceApplication.class, args);
    }

3、业务代码测试 

    @Autowired
    AnyService anyService;

    @RequestMapping(value = "/info")
    public String getInfo(){
        System.out.println("main info start");
        anyService.sys();
        System.out.println("main info end");
        return "ok";
    }

测试结果 getInfo方法在 anyService.sys(); 异步方法中未执行完 就已经返回客户端结果,与假设场景相符合。

 

猜你喜欢

转载自blog.csdn.net/u012565281/article/details/111375869