问题描述
一个方法调用另一个方法(该方法使用@Async注解)在同一个类文件中,该注解会失效!
问题复现
TestAsyncController 类
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类
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类
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注解开启新的子线程
问题原因需要各位大佬们帮忙解答!