gpt4 book ai didi

http - JDK 11 HttpClient : BindException: Cannot assign requested address

转载 作者:行者123 更新时间:2023-12-04 17:10:37 26 4
gpt4 key购买 nike

我正在使用 JDK 11 附带的新 HttpClient 发出许多请求(对 Github 的 API,但我认为这无关紧要),尤其是 GET。
对于每个请求,我构建并使用一个 HttpClient,如下所示:

final ExecutorService executor = Executors.newSingleThreadExecutor();
final HttpClient client = client = HttpClient
.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(10))
.executor(executor)
.build();
try {
//send request and return parsed response;
} finally {
//manually close the specified executor because HttpClient doesn't implement Closeable,
//so I'm not sure when it will release resources.
executor.shutdownNow();
}
这似乎工作正常,除了时不时,我收到以下异常并且请求将不再起作用,直到我重新启动应用程序:
Caused by: java.net.ConnectException: Cannot assign requested address
...
Caused by: java.net.BindException: Cannot assign requested address
at java.base/sun.nio.ch.Net.connect0(Native Method) ~[na:na]
at java.base/sun.nio.ch.Net.connect(Net.java:476) ~[na:na]
at java.base/sun.nio.ch.Net.connect(Net.java:468) ~[na:na]
请注意,这不是 JVM_Bind案件。
我没有调用 localhost 或监听 localhost 端口。我正在向外部 API 发出 GET 请求。但是,我也检查了 etc/hosts文件,看起来不错, 127.0.0.1映射到 localhost .
有谁知道为什么会发生这种情况,我该如何解决?任何帮助将不胜感激。

最佳答案

您可以尝试使用一个共享 HttpClient对于所有请求,因为它在内部管理连接池,并且可以保持同一主机的连接事件(如果支持)。在不同的 HttpClient 上执行大量请求s 无效,因为您将拥有 n线程池和 n连接池,其中 n是客户数量。而且它们不会共享与主机的底层连接。
通常,应用程序会创建 HttpClient 的单个实例。在某种 main()并将其作为依赖项提供给用户。
例如。:

public static void main(String... args) {
final HttpClient client = client = HttpClient
.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(10))
.build();
new GithubWorker(client).start();
}
更新:如何停止当前客户端
根据 HttpClientImpl.stop 中 JDK 内部私有(private)类中的 JavaDocs方法:
    // Called from the SelectorManager thread, just before exiting.
// Clears the HTTP/1.1 and HTTP/2 cache, ensuring that the connections
// that may be still lingering there are properly closed (and their
// possibly still opened SocketChannel released).
private void stop() {
// Clears HTTP/1.1 cache and close its connections
connections.stop();
// Clears HTTP/2 cache and close its connections.
client2.stop();
// shutdown the executor if needed
if (isDefaultExecutor) delegatingExecutor.shutdown();
}
这个方法是从 SelectorManager.showtdown 调用的( SelectorManagerHttpClient 的构造函数中创建),其中 shutdown() finally 中调用的方法在 SelectorManager.run() 中阻塞繁忙循环(是的,它实现了 Thread )。这个繁忙的循环是 while (!Thread.currentThread().isInterrupted()) .所以进入这个 finally阻止您需要使此循环异常失败或中断正在运行的线程。

关于http - JDK 11 HttpClient : BindException: Cannot assign requested address,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69526152/

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