欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

异步任务

程序员文章站 2022-06-27 23:22:46
@Async注解和@EnableAsync注解可以使得请求异步操作1.AsyncController.java@RestControllerpublic class AsyncController { @Autowired AsyncService asyncService; @RequestMapping("/hello") public String hello(){ asyncService.hello();//停止3秒...

@Async注解和@EnableAsync注解

可以使得请求异步操作

异步任务

1.AsyncController.java

@RestController
public class AsyncController {


    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();//停止3秒
        return "OK";
    }
}

2.AsyncService.java

@Service
public class AsyncService {


    //告诉Spring这是一个异步的方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("数据正在处理。。。");
    }
}

3.开启异步任务

//开启异步注解功能
@EnableAsync
@SpringBootApplication
public class Springboot09TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot09TestApplication.class, args);
    }
}

运行后,web请求页面直接返回OK给用户,然后3秒后返回数据正在处理。。。

本文地址:https://blog.csdn.net/qq_43891148/article/details/111907645

相关标签: SpringBoot