英文:
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论