![](/img/trans.png)
[英]Does java completableFuture has method returning CompletionStage<U> to handle exception?
[英]How to handle exception of CompletableFuture get() method
我需要向第 3 方 url 發送請求,所以我在getStatus()
方法上使用@Async
,該方法返回enum
的CompletableFuture
,如果拋出TimeoutException
,我想將狀態視為 DOWN 或如何捕獲每個調用的InterruptedException
和ExecutionException
try {
firstAppStatus = service1.getStatus().get(20, TimeUnit.SECONDS);
} catch (TimeoutException e) {
firstAppStatus = ComponentStatusEnum.DOWN;
}
try {
secondAppStatus = service2.getStatus().get(20, TimeUnit.SECONDS);
} catch (TimeoutException e) {
secondAppStatus = ComponentStatusEnum.DOWN;
}
try {
thirdAppStatus = service3.getStatus().get(20, TimeUnit.SECONDS);
} catch (TimeoutException e) {
thirdAppStatus = ComponentStatusEnum.DOWN;
}
我知道這段代碼將按順序執行,所以如何在不更改客戶端請求超時的情況下異步運行它們
如果我理解正確,你想要這樣的東西:
// allow all three requests to run concurrently
CompletableFuture<ComponentStatusEnum> status1 = service1.getStatus();
CompletableFuture<ComponentStatusEnum> status2 = service2.getStatus();
CompletableFuture<ComponentStatusEnum> status3 = service3.getStatus();
// wait for either, the completion of all three or the timeout, whatever comes first
try {
CompletableFuture.allOf(status1, status2, status3).get(20, TimeUnit.SECONDS);
} catch(TimeoutException|InterruptedException|ExecutionException ex) {
// no action, as all cases are handled below
}
// get results with fall-backs on timeout
firstAppStatus = status1.getNow(ComponentStatusEnum.DOWN);
secondAppStatus = status2.getNow(ComponentStatusEnum.DOWN);
thirdAppStatus = status3.getNow(ComponentStatusEnum.DOWN);
首先,如果要允許所有請求並行運行,請不要立即查詢結果。 然后,使用allOf
,您可以通過一個超時等待所有操作完成。
getNow
是在可用時立即獲取結果的正確操作,如果操作尚未完成,則為指定的回退值。 原則上,操作可能會在收到TimeoutException
和調用getNow
之間的很短的時間內 window 完成,但這不會對您的應用程序邏輯造成任何問題。
關於異常處理,當底層操作失敗時, getNow
行為類似於join()
拋出未經檢查的CompletionException
而不是檢查的ExecutionException
。 如果你沒有捕捉到它,它就會傳播給調用者,如果你對這種情況沒有特殊處理,這是最好的選擇。 如果超時等待被中斷,它的行為就像你有一個較小的超時一樣; 操作可能已經完成或在getNow
處獲得后備值。
使用 Java 9 您可以使用completeOnTimeout
:
CompletableFuture<ComponentStatusEnum> firstAppStatus = service1.getStatus().completeOnTimeout(ComponentStatusEnum.DOWN, 20, TimeUnit.SECONDS);
更多信息在這里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.