@Async注解的坑

问题描述

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

问题复现

TestAsyncController 类
java 复制代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestAsyncController {

    private static final Logger logger = LoggerFactory.getLogger(TestAsyncController.class);

    @PostMapping("/test")
    public void test() {
        logger.info("测试异步开始...");
        try {
            test1();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("测试异步结束...");
    }

    @Async
    public void test1(){
        for(int i=0;i<5;i++){
            logger.info("i={}",i);
        }
    }
}
问题测试结果

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

问题解决

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

TestAsyncService类
java 复制代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class TestAsyncService {

    private static final Logger logger = LoggerFactory.getLogger(TestAsyncService.class);

    @Async
    public void test1(){
        for(int i=0;i<5;i++){
            logger.info("i={}",i);
        }
    }
}
TestAsyncController类
java 复制代码
import com.example.demo.service.TestAsyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestAsyncController {

    private static final Logger logger = LoggerFactory.getLogger(TestAsyncController.class);

    @Autowired
    private TestAsyncService asyncService;

    @PostMapping("/test")
    public void test() {
        logger.info("测试异步开始...");
        try {
            asyncService.test1();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("测试异步结束...");
    }
}

测试结果

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

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

相关推荐
星辰离彬4 分钟前
Java 与 MySQL 性能优化:MySQL连接池参数优化与性能提升
java·服务器·数据库·后端·mysql·性能优化
半桔4 分钟前
【Linux手册】从接口到管理:Linux文件系统的核心操作指南
android·java·linux·开发语言·面试·系统架构
nightunderblackcat13 分钟前
新手向:实现ATM模拟系统
java·开发语言·spring boot·spring cloud·tomcat·maven·intellij-idea
Bug退退退12318 分钟前
RabbitMQ 高级特性之延迟队列
java·spring·rabbitmq·java-rabbitmq
先睡22 分钟前
RabbitMQ
java
笑衬人心。23 分钟前
Java 17 新特性笔记
java·开发语言·笔记
麦兜*1 小时前
Spring Boot 企业级动态权限全栈深度解决方案,设计思路,代码分析
java·spring boot·后端·spring·spring cloud·性能优化·springcloud
ruan1145142 小时前
MySQL4种隔离级别
java·开发语言·mysql
Hellyc6 小时前
基于模板设计模式开发优惠券推送功能以及对过期优惠卷进行定时清理
java·数据库·设计模式·rocketmq