Vertx HttpClient不会超时

时间:2017-11-01 06:53:58

标签: httpclient vert.x

我发布的不是整个代码,而是我认为对我的问题很重要的代码片段。 我已经设置了HttpClientOptions,如下所示。

HttpClientOptions clientOptions = new HttpClientOptions()
                .setDefaultHost(host)
                .setDefaultPort(port)
                .setMaxPoolSize(config.getMaxPoolSize())
                .setConnectTimeout(config.getTimeout());
HttpClient httpClient = vertx.createHttpClient(clientOptions);

然后我使用此客户端发布邮件请求,如下所示:

httpClient.post(ePoint, httpClientResponse -> {
            httpClientResponse.bodyHandler(body -> {
                    if (body.length() == 0) {
                        ctx.fail();
                        return;
                    }
                    String bodyString = body.toString();
                    int statusCode = httpClientResponse.statusCode();
                    if (statusCode != HttpStatus.SC_CREATED) {
                        ctx.fail();
                        return;
                    }
                    logger.info(ctx, "blah blah");


                        ctx.next();

                })
                .exceptionHandler(throwable -> {
                    ctx.fail();
                });

但是,如果我在接收方模拟超时,则不会调用异常处理程序。但是我在post请求异常处理程序中将时间设置如下,以便在超时时调用异常。

httpClient.post(ePoint, httpClientResponse -> {
        httpClientResponse.bodyHandler(body -> {
                if (body.length() == 0) {
                    ctx.fail();
                    return;
                }
                String bodyString = body.toString();
                int statusCode = httpClientResponse.statusCode();
                if (statusCode != HttpStatus.SC_CREATED) {
                    ctx.fail();
                    return;
                }
                logger.info(ctx, "blah blah");


                    ctx.next();

            }).setTimeout(config.getTimeout())
            .exceptionHandler(throwable -> {
                ctx.fail();
            });

这是一个Vertx错误还是设计错误。

1 个答案:

答案 0 :(得分:1)

以下方法将有效。我们需要在请求级别设置超时

HttpClientOptions clientOptions = new HttpClientOptions()
            .setDefaultHost(host)
            .setDefaultPort(port)
            .setMaxPoolSize(config.getMaxPoolSize())
            .setConnectTimeout(config.getTimeout());

HttpClient httpClient = vertx.createHttpClient(clientOptions);


HttpClientRequest request = httpClient.request(HttpMethod.GET, url, response -> {

    //process response

}).exceptionHandler(e -> {
    e.printStackTrace();
    comp.completeExceptionally(e);
});

request.putHeader("content-type", "application/json")
    .setTimeout(timeout).end();