req
req copied to clipboard
Reusing the connection pool when cloning a client
I am writing an app that need to use different clients for different goroutines (so for example, requests to same sites with different accounts will be possible because different clients use different cookiejars). So I need to clone the orginial client for each goroutine but the problem is when cloning the client, the transports are cloned too with a new connection pool and it is a big waste of resources because if I have 200 goroutines, there will be 200 connection pools to be created.
Any help for this?
Sorry for the late response, for now, the connection pool cannot be shared between multiple clients. If you want to support connection pool sharing, there are many things to consider. I will not consider it for now. I've memorized this scenario to see if it's possible to support it in the future
Hi @imroc What if I modify the code just clone the http client except for Transport? Would there be anything broken?
很抱歉响应晚了,目前,连接池无法在多个客户端之间共享。如果要支持连接池共享,需要考虑许多事项。我暂时不会考虑它。我已经记住了这个场景,看看将来是否有可能支持它
请问连接池在多线程下是并发安全的吗?我看您这句话的意思是不安全的,不知道我的理解是否正确
请问连接池在多线程下是并发安全的吗?我看您这句话的意思是不安全的,不知道我的理解是否正确
同一个client并发创建多个请求是并发安全的,这里说的跟并发安全无关
很想要这个功能,由于我的代理URL是动态变化的,setProxyURL又只能在client层级设置(),以至于不得不为每一个请求创建一个Client,这样导致创建了很多client,内存增长非常厉害(一会儿就占用了几个G的内存).如果可以在request层级设置代理URL,或者为client创建一个池,我想应该能够解决这个问题.遗憾的是目前两个功能都没有
绝大部分的请求库都不是为了爬虫而设计的,这些请求库的设计从一开始就假定网络是一个稳定的网络,从而造成了很多bug只有在爬虫场景下才能出现,
- 如果代理是隧道,请求库最佳做法是,提供一个api 可以关闭底层连接,比如当用户使用一个连接发送请求返回403的时候直接把这个连接杀死,如何还能用的话就自动放回连接池,这样的话爬虫的效率是最高的。
- 如果代理不是隧道的话,因为代理具有实效性,且客户端根据代理url 进行连接复用,会出现一种情况用户不使用这个代理了,但是连接池还有这个代理的连接存在,如果请求库没有实时监听这个代理连接的状态会导致这个资源泄露。请求库需要实时关注每一个连接的连接状态,一旦连接异常无论这个连接是否使用就及时的释放资源。