• @Async注解的坑


    问题描述

    一个方法调用另一个方法(该方法使用@Async注解)在同一个类文件中,该注解会失效!

    问题复现

    TestAsyncController 类
    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import org.springframework.scheduling.annotation.Async;
    4. import org.springframework.web.bind.annotation.PostMapping;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. @RestController
    8. @RequestMapping("/test")
    9. public class TestAsyncController {
    10. private static final Logger logger = LoggerFactory.getLogger(TestAsyncController.class);
    11. @PostMapping("/test")
    12. public void test() {
    13. logger.info("测试异步开始...");
    14. try {
    15. test1();
    16. } catch (Exception e) {
    17. e.printStackTrace();
    18. }
    19. logger.info("测试异步结束...");
    20. }
    21. @Async
    22. public void test1(){
    23. for(int i=0;i<5;i++){
    24. logger.info("i={}",i);
    25. }
    26. }
    27. }
    问题测试结果

    可以看出是全部使用的主线程

    问题解决

    将@Async注解的方法放在一个新的类文件中即可

    TestAsyncService类
    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import org.springframework.scheduling.annotation.Async;
    4. import org.springframework.stereotype.Service;
    5. @Service
    6. public class TestAsyncService {
    7. private static final Logger logger = LoggerFactory.getLogger(TestAsyncService.class);
    8. @Async
    9. public void test1(){
    10. for(int i=0;i<5;i++){
    11. logger.info("i={}",i);
    12. }
    13. }
    14. }
    TestAsyncController类
    1. import com.example.demo.service.TestAsyncService;
    2. import org.slf4j.Logger;
    3. import org.slf4j.LoggerFactory;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.PostMapping;
    6. import org.springframework.web.bind.annotation.RequestMapping;
    7. import org.springframework.web.bind.annotation.RestController;
    8. @RestController
    9. @RequestMapping("/test")
    10. public class TestAsyncController {
    11. private static final Logger logger = LoggerFactory.getLogger(TestAsyncController.class);
    12. @Autowired
    13. private TestAsyncService asyncService;
    14. @PostMapping("/test")
    15. public void test() {
    16. logger.info("测试异步开始...");
    17. try {
    18. asyncService.test1();
    19. } catch (Exception e) {
    20. e.printStackTrace();
    21. }
    22. logger.info("测试异步结束...");
    23. }
    24. }

    测试结果

    可以看出@Async注解开启新的子线程

    问题原因需要各位大佬们帮忙解答!

  • 相关阅读:
    amlogic 机顶盒关闭DLNA 后,手机还能搜到盒子
    linux文件目录
    Intel汇编-内联汇编改动的寄存器列表
    Web服务器项目实战(一)
    VUE必知必会
    系统学习Java:构建坚实的编程基础
    windows如何把已安装的nodejs高版本降级为低版本&node多环境
    一文读懂梯度下降
    自媒体从业人员常用软件/工具一览(涵盖视频、思维导图、PPT、问卷调查、H5、公众号、pdf等各方面)
    基于grpc从零开始搭建一个准生产分布式应用(6) - 03 - MapStruct高级映射
  • 原文地址:https://blog.csdn.net/qq_37342720/article/details/134382353