我有一个Spring Boot应用程序,并且想通过使用@async批注运行一个简单的Async后台任务,但是,这似乎不起作用(没有创建新线程,我等到每次调用后睡眠都结束了)功能 .. *****我的配置类:**
@Configuration
@EnableAsync
public class AsyncConfig {
}
****我的控制器:**
@GetMapping(value = "/testAsync")
@ResponseBody
public String testAsync() {
TestClass testClass = new TestClass();
System.out.println("begin of test async dates is : " + new Date());
for (int i = 0; i < 5; i++) {
testClass.asyncMethod();
}
System.out.println("end of test async dates is : " + new Date());
return "end!";
}
*****我的TestClass,其中的Async方法:**
@Service
public class TestClass {
@Async
public void asyncMethod() {
System.out.println("Execute method asynchronously. in thread : "
+ Thread.currentThread().getName());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("after sleep : " + Thread.currentThread().getName());
}
}
****运行应用程序后的输出:**
begin of test async dates is : Sat Jul 14 19:35:43 EET 2018
Execute method asynchronously. in thread : http-nio-8080-exec-1
after sleep : http-nio-8080-exec-1
Execute method asynchronously. in thread : http-nio-8080-exec-1
after sleep : http-nio-8080-exec-1
Execute method asynchronously. in thread : http-nio-8080-exec-1
after sleep : http-nio-8080-exec-1
Execute method asynchronously. in thread : http-nio-8080-exec-1
2018-07-14 19:36:22.299 INFO 3120 --- [MessageBroker-1] o.s.w.s.c.WebSocketMessageBrokerStats : WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], outboundChannelpool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], sockJsScheduler[pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]
after sleep : http-nio-8080-exec-1
Execute method asynchronously. in thread : http-nio-8080-exec-1
after sleep : http-nio-8080-exec-1
end of test async dates is : Sat Jul 14 19:36:33 EET 2018
****注意:** -我尝试用@Component注释TestClass,但没有用 -我尝试在应用程序级别和方法级别上都添加一个执行程序,但是得到的结果相同。
请帮助我,我花了5个小时没有运气
答案 0 :(得分:2)
将TestClass自动装配到控制器中,使控制器的实例成员具有TestClass类型,并为其添加注释Autowire。
当您自己实例化它时,Spring并不了解异步注释,并且对它的调用将在调用线程中运行。