Springboot Async方法在同一线程中运行 [英] Springboot Async method run in same thread
问题描述
我正在春季靴2中测试 @Async
,并且我遵循了一些在线教程
I am testing out @Async
in a spring boot 2, and i followed some online tutorial
我的配置类:
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(5);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("Async Process-");
executor.initialize();
return executor;
}
}
我的控制器"的片段:
@GetMapping("/test/async")
public void testAsync() {
System.err.println("Thread in controller: " + Thread.currentThread().getName());
TestAsyncClazz clazz = new TestAsyncClazz();
clazz.testAsyncMethod();
}
我的 TestAsyncClass
:
public class TestAsyncClazz {
@Async
public void testAsyncMethod(){
System.err.println("Running async: "+ Thread.currentThread().getName());
}
}
当我检查打印行时,它表明我的两个方法都在同一线程上运行,并且未使用threadNamePrefix Async Process-
:
When i check the print line, it shows that both of my method running on the same thread, and it didn't use the threadNamePrefix Async Process-
:
Thread in controller: http-nio-8080-exec-2
Running async: http-nio-8080-exec-2
我做错了什么?我误会了吗?
What i did wrong? Did i misunderstand something?
推荐答案
之所以会发生这种情况,是因为您正在使用 new
实例化自己的类上调用异步方法:
This happens because you are calling the async method on a class that you instantiate yourself using new
:
TestAsyncClazz clazz = new TestAsyncClazz();
clazz.testAsyncMethod();
如果采用这种方式,Spring将没有机会用必要的代理类来装饰实例,该代理类提供了异步运行方法的实际功能.
If you do it this way, Spring does not have a chance to decorate the instance with the necessary proxy class that provides the actual functionality to run the method asynchronously.
这只会按您期望的方式在Spring bean上起作用-换句话说,不要自己实例化 TestAsyncClazz
;定义该类的Spring bean实例,将该bean自动装配到控制器中,然后在bean上调用该方法.
This will only work the way you expect on Spring beans - in other words, do not instantiate TestAsyncClazz
yourself; define a Spring bean instance of the class, autowire that bean into your controller and then call the method on the bean.
示例:
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(5);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("Async Process-");
executor.initialize();
return executor;
}
// Define a Spring bean of type TestAsyncClazz
@Bean
public TestAsyncClazz testAsyncClazz() {
return new TestAsyncClazz();
}
}
@Controller
public class MyController {
// Inject the bean here
@Autowired
private TestAsyncClazz testAsyncClass;
@GetMapping("/test/async")
public void testAsync() {
System.err.println("Thread in controller: " +
Thread.currentThread().getName());
// Use the bean instead of instantiating the class yourself
testAsyncClass.testAsyncMethod();
}
}
这篇关于Springboot Async方法在同一线程中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!