如何在Java中的WebClient中使用Vertx路由器中的期货

时间:2018-08-01 15:24:48

标签: java asynchronous future vert.x web-client

我有一个带有路由器端点的Vertx应用程序:

router.route(HttpMethod.GET, Constants.ENDPOINT).blockingHandler(this::getItems);

此路由器调用一个方法,该方法应该在浏览器或任何正在调用此端点的客户端中返回JSON对象。 JSON对象实际上来自完全不同的服务。我正在使用Vert.x的WebClient库来调用此服务。

    private void getItems(RoutingContext routingContext) {
    HttpServerResponse response = routingContext.response();
    response.setChunked(true);
    response.putHeader("content-type", "text/plain");
    response.putHeader("Access-Control-Allow-Origin", "*");
    JsonObject data = new JsonObject();
    WebClient webClient = WebClient.create(vertx);
    webClient.post(80, "my-site.com", "/api/items")
        .as(BodyCodec.jsonArray())
        .putHeader("Accept", "application/json")
        .putHeader("Content-Type", "application/json")
        .sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
            if (ar.succeeded()) {
                HttpResponse<JsonArray> result = ar.result();
                JsonArray body = result.body();
                System.out.println(body);
                data.put("data", body.getJsonObject(0));
            } else {
                data.put("data", ar.cause().getMessage());
            }
        }); 
    response.write(data.encode());
    routingContext.response().end();
}

我从my-site.com获得的数据很好,并使用System.out命令显示在控制台中。问题是我无法进入response.write

阅读后,我发现这与期货有关。我不太了解这个概念,所以我已经做了很多阅读,但是找不到适合我特定代码的示例。

我将如何实现期货,以便将从my-site.com接收到的数据放入我的Json对象(data)中,然后可以在response.write中使用?

2 个答案:

答案 0 :(得分:2)

由于Webclient是异步的,因此在impl中,数据将是一个空的JSON对象。您正在将响应写入客户端之前,Webclient的响应已准备就绪。

将写入内容移至webclient响应中,并在此处结束上下文。例如:

NAMESPACE

答案 1 :(得分:1)

关于async coordination的Vert.x文档非常好,并在示例中使用了期货。这是我使用Vert.x期货实现它的方式:

private void getItems(RoutingContext routingContext) {
        HttpServerResponse response = routingContext.response();
        response.setChunked(true);
        response.putHeader("content-type", "text/plain");
        response.putHeader("Access-Control-Allow-Origin", "*");
        // init a future that should hold a JsonObject result
        Future<JsonObject> future = Future.future();
        JsonObject data = new JsonObject();
        WebClient webClient = WebClient.create(vertx);
        webClient.post(80, "my-site.com", "/api/items")
                .as(BodyCodec.jsonArray())
                .putHeader("Accept", "application/json")
                .putHeader("Content-Type", "application/json")
                .sendJsonObject(new JsonObject().put("mutator", "*"), ar -> {
                    if (ar.succeeded()) {
                        HttpResponse<JsonArray> result = ar.result();
                        JsonArray body = result.body();
                        System.out.println(body);
                        data.put("data", body.getJsonObject(0));
                        // set future to be completed, with data object as its JsonObject result
                        future.complete(data);
                    } else {
                         data.put("data", ar.cause().getMessage());
                         future.complete(data);
                         // we can also set the future as failed and give it a Throwable
                        // future.fail(ar.cause());
                    }
                });
        // handle when the future is completed
        future.setHandler(jsonObjectAsyncResult -> {
            if(jsonObjectAsyncResult.succeeded()) {
                response.write(data.encode());
                routingContext.response().end();
            }
        });
    }