当前位置:   article > 正文

Spring boot实现异步_springboot异步写数据库

springboot异步写数据库

1.首先去主类上开启@EnableAsync

  1. @SpringBootApplication
  2. @EnableScheduling
  3. @EnableAsync //开启异步
  4. public class NginxApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(NginxApplication.class, args);
  7. }
  8. }

2.新建一个类,添加@Async注解

  1. @Service
  2. public class Testasync {
  3. @Async
  4. public void async1() {
  5. System.out.println("async1异步id:"+Thread.currentThread().getId());
  6. }
  7. @Async
  8. public void async2() {
  9. System.out.println("async2异步id:"+Thread.currentThread().getId());
  10. }
  11. }

3.调用此方法

  1. @Controller
  2. @RequestMapping("/test")
  3. public class zhu {
  4. @Autowired
  5. private Testasync async;
  6. @RequestMapping("/async")
  7. @ResponseBody
  8. public String test() {
  9. System.out.println("Thread id:"+Thread.currentThread().getId());
  10. async.async1();
  11. async.async2();
  12. return "进入了异步方法";
  13. }
  14. }

打印出显示出不同的线程id:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/954293
推荐阅读
相关标签
  

闽ICP备14008679号