在并发应用程序中使用HTTP客户端的最佳方法是什么?

huangapple go评论97阅读模式
英文:

Best way to use HTTP client in a concurrent application

问题

首先,我将描述我的情况。
我需要从我的应用程序中对多个API进行HTTPS请求,并且它们应该并发运行。
我想知道是否应该在每个goroutine中使用单独的HTTP客户端,还是可以在所有goroutines之间共享一个客户端。当然,我希望能够享受HTTP客户端提供的连接重用/池化功能,但我担心它是否是线程(即goroutine)安全的,以及客户端是否会并发运行请求,还是实际上是按顺序运行的?

英文:

First I'll describe my case.
I have to do HTTPS requests to several APIs from my application and they should be ran concurrently.
I want to know if I should use a separate HTTP client per goroutine or I can share one client across all goroutines. Of course I'd like to enjoy connection reusing/pooling offered by the HTTP client, but I am concerned about it being thread(aka goroutine)-safe and if the client will run requests concurrently or they'll in fact be sequenced?

答案1

得分: 35

根据文档(https://golang.org/src/net/http/client.go),Http客户端是线程安全的:

> 客户端可以被多个goroutine并发使用而不会出现问题。

英文:

Http clients are thread safe according to the docs (https://golang.org/src/net/http/client.go):

> Clients are safe for concurrent use by multiple goroutines.

答案2

得分: 3

另一个问题是你应该使用一个客户端还是每个请求使用一个客户端。根据https://pkg.go.dev/net/http#pkg-overview,你应该使用一个客户端。

“客户端和传输是可以被多个goroutine并发使用的,并且为了效率应该只创建一次并重复使用。”

英文:

The other question was should you use one client or one per request. You should use one client as per
https://pkg.go.dev/net/http#pkg-overview

"Clients and Transports are safe for concurrent use by multiple goroutines and for efficiency should only be created once and re-used"

huangapple
  • 本文由 发表于 2016年4月21日 23:16:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/36773837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定