【问题标题】:Thread blocked when calling dynamoDB in vert.x app在 vert.x 应用程序中调用 dynamoDB 时线程被阻塞
【发布时间】:2022-08-12 16:33:46
【问题描述】:

我正在使用 vert.x,我正在尝试列出我的 DynamoDB 表。以下是我构建 DynamoDB 客户端的方法。

private static DynamoDbAsyncClient buildDynamoDBAsyncClient(final Vertx vertx) {
        return VertxSdkClient.withVertx(DynamoDbAsyncClient.builder(), vertx.getOrCreateContext())
                .build();
    }

这是我提出的要求

CompletableFuture<ListTablesResponse> response = client.listTables(ListTablesRequest.builder()
                .build());

        // Map the response to another CompletableFuture containing just the table names
        CompletableFuture<List<String>> tableNames = response.thenApply(ListTablesResponse::tableNames);

        // When future is complete (either successfully or in error) handle the response
        tableNames.whenComplete((tables, err) -> {
                if (tables != null) {
                    tables.forEach(System.out::println);
                } else {
                    // Handle error
                    err.printStackTrace();
                }
          
                client.close();
        });
        tableNames.join();

我收到阻塞线程的警告,然后是请求超时。我究竟做错了什么?先感谢您。

  • tableNames.join() 阻塞线程直到操作完成。相反,它应该允许CompletableFuture 传播给调用者。如果您包含更多上下文代码,我可以写一个更完整的答案
  • 如果请求超时解决 Future 花费的时间比您的请求花费的时间要多... dynamoDb 非常慢,所以我想您需要更好的查询或处理后端中的内容,而不是在一个请求的范围内需要几秒钟才能完成。

标签: java amazon-dynamodb vert.x


【解决方案1】:

正如蒂姆在评论中所说,tablesName.join() 阻塞了线程,你应该让CompletableFuture 处理异步。

尝试这个:

private Future<ListTablesResponse> listTables() {
        Promise<ListTablesResponse> promise = Promise.promise();
        CompletableFuture<ListTablesResponse> response = client.listTables();

        response.handleAsync((result, error) -> {
            if (error == null) {
                promise.complete(result);
            } else {
                promise.fail(error);
            }
            return null;
        });

        return promise.future();
    }

然后在您的 vertx 请求处理程序中:

this.listTables()
        .onSuccess(listTablesResponse -> {...})
        .onFailure(throwable -> {...});

【讨论】:

    猜你喜欢
    • 2013-11-16
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多