2017-04-20 62 views
0

應用程序聲明使用單一方法發送通知的接口,返回類型爲ListenableFuture<>是在單獨的線程中執行ListenableFuture返回值的bean方法嗎?

對於郵件服務I 如果在我的批處理作業中配置錯誤(例如,如果SMTP服務器已關閉或主機未解析),則不會看到例外

調試表明上:

MailNotificationService mailService = applicationContext.getBean(MailNotificationService.class); 

我收到代理上的方法調用:

mailService.send(mime); 

解決了與堆棧:

at org.springframework.aop.interceptor.AsyncExecutionInterceptor.invoke(AsyncExecutionInterceptor.java:101) 
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) 
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) 

invoke文件說:

* Intercept the given method invocation, submit the actual calling of the method to 
* the correct task executor and return immediately to the caller. 

經過一些步驟後,我看到新的線程SimpleAsyncTaskExecutor-1和服務在這裏執行。

它看起來像在單獨的線程和異常中執行的服務不會傳播到原始線程(如果它有意義的話)。

它是正確的,對bean方法與ListenableFuture<>收益型彈簧在單獨的線程中執行呢?

NB我的原始問題是我在通知服務中出現錯誤(未記錄跟蹤)時失明。郵件服務將拋出unchecked org.springframework.mail.MailException和發現的唯一出路是Exception伐木包裝.send()方法:

@Autowired 
private JavaMailSender mailSender; 

public void notify() { 
    try { 
     mailSender.send(mime); 
    } catch (Exception ex) { 
     log.warn("Can't deliver mail", ex); 
    } 
} 
+1

https://spring.io/guides/gs/async-method/ - 看看這裏,我想方法@Async註解,而異步啓動 – white

+0

** @白**感謝!我沒有注意到服務方法上的'@ Async'註釋和配置類上的'@ EnableAsync'。春天變得怪異。 – gavenkoa

回答

1

由於白色預測我對服務方法@Async註釋和@EnableAsync上配置類。

異常處理部分中描述:

http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/htmlsingle/#scheduling-annotation-support-exception

Future返回類型的情況下(ListenableFuture是它的亞型)的異常傳播到未來的對象,並且可以從Future.get()方法調用發生異常ExecutionException.getCause()被檢索。

在我的情況下,我忽略返回類型(不要撥打.get())。所以異常沒有被捕獲和記錄。正如我最初寫的,在這種情況下,記錄應該在任務本身完成。

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutionException.html

相關問題