我想使用CompletableFuture提供的方法異步呼叫 DynamoDB 的 REST 呼叫:
private CompletableFuture<UpdateItemResult> updateDynamodbAsync(UpdateItemRequest request) {
return CompletableFuture.supplyAsync(() -> {
UpdateItemResult result = amazonDynamoDBClient.updateItem(request);
return result;
});
}
代碼的執行如下:
UpdateItemResult result = null;
CompletableFuture<UpdateItemResult> updateItemResultCompletableFuture = updateDynamodbAsync(updateItemRequest);
while (true) {
if (updateItemResultCompletableFuture.isDone()) {
result = updateItemResultCompletableFuture.get(3000, TimeUnit.MILLISECONDS);
break;
}
}
該while回圈阻塞,直到請求已完成,我覺得這個塊的程序。代碼是否仍然是異步的,如果不是,我該如何改進它?
其次,我將使用空檢查單獨處理錯誤:
if (result == null) {
LOGGER.debug("The update operation in the DynamoDB is not sucessful .......");
return dbPresistenceResponseMap;
}
好嗎?
uj5u.com熱心網友回復:
您的while(true)回圈可以簡化為updateItemResultCompletableFuture.join()或.get()。
當然,同時使用 while 和 join 都會阻塞該程序,因此即使您 DynamoDB 是異步創建的,您也不會從中受益。保持執行異步的正確方法是使用其中一種then…()方法鏈接未來的呼叫。
例如,您的錯誤處理可以通過
return updateItemResultCompletableFuture.thenApply(result -> {
if (result == null) {
LOGGER.debug("The update operation in the DynamoDB is not sucessful .......");
return dbPresistenceResponseMap;
}
return /* success result */;
}
如果呼叫者還需要使用該結果執行某些操作,則您也必須回傳 a CompletableFuture(因此return我將其放在此處的第一行)。這將允許它鏈接更多的呼叫。
附帶說明一下,在supplyAsync()不提供 an 的情況下使用Executor將使您的呼叫運行在common 上ForkJoinPool,它旨在運行 CPU 密集型任務。由于這是一個 I/O 操作,您應該提供自己的Executor.
最后,我不熟悉 AWS,但請注意 DynamoDB 也有一個async client,您可能應該使用它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/401247.html
標籤:爪哇 异步 亚马逊动态数据库 java.util.concurrent 可完成的未来
下一篇:Rust異步借用生命周期
