我正在我的代碼中嘗試異步行程。我寫了如下代碼。但是異步行程不起作用。執行緒名稱“”本身未顯示在日志中。看起來服務類不是在尋找 bean 'asyncExecutor'。我在這里缺少什么。
@SpringBootApplication
@EnableAsync
public class MyMainApplication {
@Bean(name = "asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(3);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("AsynchThread-");
executor.initialize();
return executor;
}
public static void main(String[] args) {
SpringApplication.run(MyMainApplication.class, args);
}
}
服務等級
public void getSampleDetails(String param1, String param2) {
log.info("Inside - getSampleDetails");
CompletableFuture<Map<String, String>> sampleMap1 = null;
CompletableFuture<Map<String, String>> sampleMap2 = null;
CompletableFuture<Map<String, String>> sampleMap3 = null;
sampleMap1 = getSampleMap1(param1, param2);
sampleMap2 = getSampleMap2(param1, param2);
sampleMap3 = getSampleMap3(param1, param2);
// Wait until they are all done
CompletableFuture.allOf(sampleMap1, sampleMap2, sampleMap3).join();
}
@Async("asyncExecutor")
public CompletableFuture<Map<String, String>> getSampleMap1(String param1, String param2) throws InterruptedException {
System.out.println("Inside Method1");
..
..
}
@Async("asyncExecutor")
public CompletableFuture<Map<String, String>> getSampleMap2(String param1, String param2) throws InterruptedException {
System.out.println("Inside Method2");
..
..
}
@Async("asyncExecutor")
public CompletableFuture<Map<String, String>> getSampleMap3(String param1, String param2) throws InterruptedException {
System.out.println("Inside Method3");
..
..
}
執行緒名稱未顯示,異步行程未發生日志:
[ main]o.s.s.concurrent.ThreadPoolTaskExecutor Initializing ExecutorService
[ main]o.s.s.concurrent.ThreadPoolTaskExecutor Initializing ExecutorService 'asyncExecutor1'
[ main]o.s.s.c.ThreadPoolTaskScheduler Initializing ExecutorService 'taskScheduler'
[ main]o.s.b.w.embedded.tomcat.TomcatWebServer Tomcat started on port(s): 32182 (http) with context path '/myapplication'
[ main]MyMainApplication Started MyMainApplication in 46.662 seconds (JVM running for 48.024)
[exec-1]e-myapplication] Initializing Spring DispatcherServlet 'dispatcherServlet'
[exec-1]o.s.web.servlet.DispatcherServlet Initializing Servlet 'dispatcherServlet'
[exec-1]o.s.web.servlet.DispatcherServlet Completed initialization in 8 ms
[exec-1]Inside - getSampleDetails
[exec-1]Inside Method1
[exec-1]Inside Method2
[exec-1]Inside Method3
uj5u.com熱心網友回復:
spring 掃描 bean 時,會掃描方法中是否包含 @Async 注解。如果包含,spring會為這個bean動態生成一個子類(即代理類,proxy),代理類繼承原bean。這時候,被注解的方法被呼叫的時候,其實是被代理類呼叫的,代理類在呼叫的時候加入了異步效果。但是如果這個注解的方法被同一個類中的其他方法呼叫,方法呼叫并沒有經過代理類,而是直接通過原始bean,所以沒有異步效果,我們看到的現象是@Async注釋無效。
你可以嘗試這樣的事情:
- 呼叫和任務應該放在不同的類中。
- 在啟動類中添加注解:@EnableAspectJAutoProxy(exposeProxy = true)
- 在ServiceManager中,使用AopContext.currentProxy()獲取Service的代理類,然后呼叫事務方法強制通過代理類激活事務切面。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417769.html
標籤:
下一篇:異步等待未按預期回傳值
