首页 > 解决方案 > HttpTimeout 优雅地关闭连接

问题描述

我正在使用 java Apache HttpClient 请求超时为 10 秒的资源 (B)。如果超时超过其他应用程序服务器上的损坏管道。

因为应用程序 B 的 Nginx 没有缓存响应。如何优雅地关闭连接,使其他应用服务器(B)不会遇到断管异常。

标签: javanginxtomcatcachingapache-httpclient-4.x

解决方案


如果您使用的是足够新的 HttpClient,您不能做这样的事情(我刚刚找到了其他人写的一个片段......但请参阅下面我添加的地方###)

   HttpClient client = HttpClient.newHttpClient();

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost:8081/test/resource"))
        .header("Accept", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString("ping!"))
        .build();

    CompletableFuture<HttpResponse<String>> completableFuture =
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
    completableFuture
        .completeOnTimeout(DEFAULT_RESPONSE, 1, TimeUnit.SECONDS)  //  ### ADD THIS the HttpClientRequest actually continues but the future has timed out so the user of the client progresses  ??
        .thenApplyAsync(HttpResponse::headers)
        .thenAcceptAsync(System.out::println);
    HttpResponse<String> response = completableFuture.join();

推荐阅读