简体   繁体   English

为什么要复用 Go 的 http.Client 实例?

[英]Why should Go’s http.Client instances be reused?

The Go documentation says Go 文档

The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed.客户端的传输通常具有内部 state(缓存的 TCP 连接),因此客户端应该被重用而不是根据需要创建。 Clients are safe for concurrent use by multiple goroutines.客户端可以安全地被多个 goroutine 并发使用。

Why does Client reuse help with preserving the Transport's internal state, given that I can instantiate a transport and pass it to single-use Client instances like this:考虑到我可以实例化传输并将其传递给一次性客户端实例,为什么客户端重用有助于保留传输的内部 state:

client := &http.Client{Transport: transport}

Why should Go's http.Client instances be reused?为什么要复用 Go 的 http.Client 实例?

There are many reasons.有很多原因。 The most universal one is to allow reusing existing HTTP connections.最通用的一种是允许重用现有的 HTTP 连接。 If you use a new http.Client instance for every request, you can never take advantage of existing HTTP connections, which will result in more overhead and slower performance for most common uses.如果对每个请求都使用新的http.Client实例,则永远无法利用现有的 HTTP 连接,这将导致大多数常见用途的开销更大,性能更慢。

Another common reason would be to use a cookie jar, if you're calling an HTTP server that uses cookies.如果您正在调用使用 cookies 的 HTTP 服务器,则另一个常见原因是使用 cookie jar。

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

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