gpt4 book ai didi

java - 从 try 资源结构返回 Future

转载 作者:行者123 更新时间:2023-11-30 07:32:05 25 4
gpt4 key购买 nike

我有以下方法,它使用 Apache Commons Http 客户端发送异步 GET 到给定的 URI 并返回 Future 的响应。

CloseableHttpAsyncClient 实现 Closeable,因此我使用 try/resource 构造。

public static Future<HttpResponse> sendAsyncGet(String uri) throws IOException {
try (CloseableHttpAsyncClient asyncHttpClient = HttpAsyncClients.createDefault()) {
asyncHttpClient.start();
HttpGet httpGet = new HttpGet(uri);
return asyncHttpClient.execute(httpGet, null);
}

下面您可能会看到用法:

Future<HttpResponse> future = sendAsyncGet("http://www.apache.org");
future.get(3, TimeUnit.SECONDS);

问题是,当我在 future 上调用 get 时,它不会返回所需的 HttpResponse。如果我使用重载的 get() 方法,它会等待直到超时或永远。我猜这是因为 try/resource 没有正确释放。

如何改进给定的方法/代码以便能够正确使用:方法主体中包含 try/resource 结构的 Future?

更新:

这是 Maven 依赖项:

   <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.1</version>
<scope>test</scope>
</dependency>

最佳答案

尝试使用资源将在收到响应之前关闭异步客户端。

您可能希望从传递给执行调用的 future 回调中关闭异步客户端。

public static Future<HttpResponse> sendAsyncGet(String uri) throws IOException {
final CloseableHttpAsyncClient asyncHttpClient;

asyncHttpClient = HttpAsyncClients.createDefault();
asyncHttpClient.start();

return asyncHttpClient.execute(new HttpGet(uri), new FutureCallback<HttpResponse>() {
private void close() {
try {
asyncHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void completed(HttpResponse response) {
close();
System.out.println("completed");
}

@Override
public void failed(Exception e) {
close();
e.printStackTrace();
}

@Override
public void cancelled() {
close();
System.out.println("cancelled");
}
});
}

关于java - 从 try 资源结构返回 Future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35961356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com