php小编西瓜注意到,使用Go语言进行多线程请求时,有时候并不能获得高的请求每秒(RPS)速度。尽管Go语言在并发处理方面表现出色,但在某些情况下,多线程请求的效率并不高。这可能是由于网络延迟、资源竞争等因素导致的。在这篇文章中,我们将探讨这个问题,并提供一些可能的解决方案来提高Go语言多线程请求的RPS。
问题内容
我正在尝试编写一个多线程客户端来测试我的服务器。当我使用 2 个 goroutine 时,一切都很好,我得到 50k rps 并且我的 cpu 负载正常,但是当我创建超过 2 个 goroutine 时,rps 下降到 3k,但我的 cpu 负载超过了。尽管当我多次运行客户端代码时(例如同时在 3 个控制台上运行相同的代码),我获得了更多 rps,例如 80k rps。
这是我的客户端代码
package main import ( "fmt" "net/http" "os" "sync" "time" ) func main() { requesturl := fmt.sprintf("http://localhost:%d/home", 3333) var wg sync.waitgroup wg.add(4) req, err := http.newrequest(http.methodget, requesturl, nil) if err != nil { fmt.printf("client: could not create request: %s\n", err) os.exit(1) } for i := 0; i < 4; i++ { go func() { defer wg.done() client := http.client{ timeout: 30 * time.second, } for { client.do(req) } }() } wg.wait() }
这是我的服务器端代码
package main import ( "errors" "fmt" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "log" "net/http" "os" "sync" ) // log handling func openlogfile(path string) (*os.file, error) { logfile, err := os.openfile(path, os.o_wronly|os.o_append|os.o_create, 0644) if err != nil { return nil, err } return logfile, nil } // variables of counter in metric var okstatuscounter = prometheus.newcounter( prometheus.counteropts{ name: "ok_request_count", help: "number of 200", }, ) func listener(serverlog *log.logger) http.handlerfunc { return func(w http.responsewriter, r *http.request) { //metric okstatuscounter.inc() w.writeheader(http.statusok) } } func main() { //metric prometheus.mustregister(okstatuscounter) //log handling filesimpleserverlog, err := openlogfile("simpleserver/simpleserverlog.log") if err != nil { log.fatal(err) } serverlog := log.new(filesimpleserverlog, "[simple server]", log.lstdflags|log.lshortfile|log.lmicroseconds) var wg sync.waitgroup wg.add(1) //server: go func() { defer wg.done() mux := http.newservemux() mux.handlefunc("/home", listener(serverlog)) mux.handle("/metrics", promhttp.handler()) server := http.server{ addr: fmt.sprintf(":%d", 3333), handler: mux, } if err := server.listenandserve(); err != nil { if !errors.is(err, http.errserverclosed) { serverlog.printf("error running http server: %s\n", err) } } }() wg.wait() }
一开始我以为 go 可能会使用一个端口来进行所有客户端连接,但是当我用 netstat 检查它时,它使用了多个端口。我尝试搜索但找不到合适的答案
我尝试了sync.mutex:
var mu sync.Mutex ... for i := 0; i < 1000; i++ { go func() { defer wg.Done() client := http.Client{ //Timeout: 30 * time.Second, } for { mu.Lock() _, err := client.Do(req) if err != nil { clientLog.Printf("client: error making http request: %s\n", err) os.Exit(1) } mu.Unlock() } }() } wg.Wait() ...
通过上述更改,我获得了 13k rps,并且我的 cpu 负载正常,但这根本不够
解决方法
由于您仅向一台主机发送请求,因此 http 传输的默认值不适合您。最好根据您的情况手动设置参数:
t := http.DefaultTransport.(*http.Transport).Clone() t.MaxIdleConns = 100 t.MaxConnsPerHost = 100 t.MaxIdleConnsPerHost = 100 httpClient = &http.Client{ Timeout: 10 * time.Second, Transport: t, }
有关更多信息,您可以阅读这里。
以上是go 中的多线程请求并且没有获得高 RPS的详细内容。更多信息请关注PHP中文网其他相关文章!

Golang和Python的主要区别在于并发模型、类型系统、性能和执行速度。1.Golang使用CSP模型,适用于高并发任务;Python依赖多线程和GIL,适合I/O密集型任务。2.Golang是静态类型,Python是动态类型。3.Golang编译型语言执行速度快,Python解释型语言开发速度快。

Golang通常比C 慢,但Golang在并发编程和开发效率上更具优势:1)Golang的垃圾回收和并发模型使其在高并发场景下表现出色;2)C 通过手动内存管理和硬件优化获得更高性能,但开发复杂度较高。

Golang在云计算和DevOps中的应用广泛,其优势在于简单性、高效性和并发编程能力。1)在云计算中,Golang通过goroutine和channel机制高效处理并发请求。2)在DevOps中,Golang的快速编译和跨平台特性使其成为自动化工具的首选。

Golang和C 在执行效率上的表现各有优势。1)Golang通过goroutine和垃圾回收提高效率,但可能引入暂停时间。2)C 通过手动内存管理和优化实现高性能,但开发者需处理内存泄漏等问题。选择时需考虑项目需求和团队技术栈。

Golang更适合高并发任务,而Python在灵活性上更有优势。1.Golang通过goroutine和channel高效处理并发。2.Python依赖threading和asyncio,受GIL影响,但提供多种并发方式。选择应基于具体需求。

Golang和C 在性能上的差异主要体现在内存管理、编译优化和运行时效率等方面。1)Golang的垃圾回收机制方便但可能影响性能,2)C 的手动内存管理和编译器优化在递归计算中表现更为高效。

selectgolangforhighpperformanceandcorrency,ifealforBackendServicesSandNetwork程序; selectpypypythonforrapiddevelopment,dataScience和machinelearningDuetoitsverserverserverserversator versator anderticality andextility andextentensivelibraries。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。 Golang以其并发模型和高效性能着称,Python则以简洁语法和丰富库生态系统着称。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用