[英]Is bean method with ListenableFuture return value executed in separate thread?
應用程序聲明接口,以單一方法使用ListenableFuture<>
返回類型發送通知。
對於郵件服務,我在批處理作業中沒有看到配置錯誤(例如,如果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
和服務。
看起來服務是在單獨的線程中執行的,並且異常不會傳播到原始線程(如果它確實有意義)。
對於具有ListenableFuture<>
返回類型Spring的bean方法,在單獨的線程中執行它們是否正確?
注意:我的原始問題是,如果通知服務出錯(不記錄跟蹤),我將視而不見。 郵件服務會拋出未經檢查的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);
}
}
正如白人預測的那樣,我在服務方法上有@Async批注,在配置類上有@EnableAsync。
小節中描述的異常處理:
如果是Future
返回類型( ListenableFuture
是它的子類型),則異常會傳播到Future
對象,並且可以從在Future.get()
方法調用中發生的ExecutionException.getCause()
異常中檢索。
就我而言,我忽略了返回類型(不要調用.get()
)。 因此未捕獲並記錄異常。 正如我最初寫的那樣,在這種情況下,應在任務本身中進行日志記錄。
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutionException.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.