【问题标题】:DynamoDB Asynchronous REST callDynamoDB 异步 REST 调用
【发布时间】:2021-12-31 04:11:09
【问题描述】:

我想使用CompletableFuture 异步调用 DynamoDB 并提供方法:

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;
        }

还好吗?

【问题讨论】:

    标签: java asynchronous amazon-dynamodb java.util.concurrent completable-future


    【解决方案1】:

    您的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 */;
    }
    

    如果调用者还需要对该结果执行某些操作,则您还必须返回CompletableFuture(因此return 我放在第一行)。这将允许它链接更多的调用。

    附带说明,在不提供Executor 的情况下使用supplyAsync() 将使您的调用在the common ForkJoinPool 上运行,该the common ForkJoinPool 旨在运行受CPU 限制的任务。由于这是一个 I/O 操作,您应该提供自己的Executor

    最后,我对 AWS 不熟悉,但请注意,DynamoDB 也有一个async client,你应该可以使用它。

    【讨论】:

    • 我想通知您,我根据您的建议编写代码,这非常有帮助。目前,我尝试使用带有 Java SDK 异步代码的本机实现来实现。谢谢。
    猜你喜欢
    • 2011-09-24
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    相关资源
    最近更新 更多