简体   繁体   English

如何限制 java.net.http.HttpClient 的连接

[英]How to limit connections for java.net.http.HttpClient

How to limit the number of connection/request for java.net.http.HttpClient?如何限制java.net.http.HttpClient的连接数/请求数?

I see I can set an Executor to HttpClient but I don't know: if I limit the number of thread in pool of Executor, is it limit also the number of connection?我看到我可以将 Executor 设置为 HttpClient 但我不知道:如果我限制 Executor 池中的线程数,它是否也限制了连接数?

Another way to limit the number of connection?另一种限制连接数的方法?

To limit the number of concurrent requests made through the HttpClient you will have to do so at the application level.要限制通过 HttpClient 发出的并发请求数,您必须在应用程序级别这样做。 The HttpClient is purely asynchronous so limiting the number of threads in the HttpClient executor will not work. HttpClient 是纯异步的,因此限制 HttpClient 执行程序中的线程数将不起作用。 Similarly, limiting the number of connections in the keep-alive pool will not work, since the pool contains only idle connections.同样,限制 keep-alive 池中的连接数也不起作用,因为该池仅包含空闲连接。

It should be very easy to limit the number of concurrent requests at the application level by guarding the code that sends requests with a simple semaphore (see java.util.concurrent.Semaphore ).通过保护使用简单信号量发送请求的代码(请参阅java.util.concurrent.Semaphore ),在应用程序级别限制并发请求的数量应该非常容易。 To limit the number of concurrent requests to eg 10 requests, just create a semaphore with 10 permits, acquire the semaphore before sending a request and release it when the response has arrived.要将并发请求数限制为例如 10 个请求,只需创建一个具有 10 个许可的信号量,在发送请求之前获取信号量并在响应到达时释放它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM