英文:
Connection pooling: interaction of MaxIdleConnsPerHost and IdleConnTimeout in http.Transport
问题
我正在尝试使用Golang编写一个重型代理,用于访问一组Web API。为了防止端口耗尽,我决定不使用DefaultClient
,而是为http.Client
创建一个自定义实例。http.Transport
中有许多有趣的设置可以调整。
我遇到了MaxIdleConnsPerHost
和IdleConnTimeout
字段,并且有一个问题。
如果我增加MaxIdleConnsPerHost
的值,这意味着会有更多的空闲连接,但它们是可重用的空闲连接吗?换句话说,为了创建一个良好的连接池,我应该相应地增加MaxIdleConnsPerHost
的值和IdleConnTimeout
的超时时间,还是相反?
英文:
I am trying to write a heavy duty proxy to a set of web APIs in Golang. In order to prevent port exhaustion, I have decided to not use the DefaultClient
and instead create a customized instance for http.Client
. There are many interesting setting in the http.Transport
that I can play around with.
I have come across the MaxIdleConnsPerHost
and IdleConnTimeout
fields and I have this question.
If I increase the value of MaxIdleConnsPerHost
it means there will be more idle connection, but are they reusable idle connections? Or in other words, to make a decent connection pool, should I increase the value of MaxIdleConnsPerHost
together with the timeout for IdleConnTimeout
accordingly, or does it behave exactly the opposite?
答案1
得分: 3
是的,IdleConns是可重用的,因为它们是keep-alive连接。但是为了让Golang尊重keep-alive连接的可重用性,在应用程序中需要确保以下两点:
- 读取完整的响应(即ioutil.ReadAll(rep.Body))
- 调用Body.Close()
这里有一个链接提供更详细的解释。
英文:
yes, IdleConns are reusable as these are keep-alive connections. But to make golang honour the reusability of keep-alive connections you need to make sure of 2 things in your applications.
- Read until Response is complete (i.e. ioutil.ReadAll(rep.Body))
- Call Body.Close()
here's a link for more explaination.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论