答案:Golang结合testing包和goroutine可高效进行HTTP并发基准测试。通过编写串行与并发测试函数,测量目标服务的吞吐量和延迟,使用BenchmarkHTTPSingle和BenchmarkHTTPConcurrent分别模拟单请求与高并发场景,控制批处理并发数避免资源耗尽,运行测试并分析ns/op指标,结合-benchtime延长测试提升准确性,进一步可通过复用Client、启用Keep-Alive、统计P95/P99延迟等优化测试精度,评估服务性能瓶颈。

测试网络请求性能在构建高并发服务时非常关键。Golang 提供了内置的 testing 包,结合其轻量级 goroutine 特性,非常适合做 HTTP 并发基准测试。下面通过一个具体实例展示如何用 Golang 编写 HTTP 并发基准测试,帮助你评估目标服务的吞吐能力和响应延迟。
示例代码:
package main
<p>import (
"net/http"
"time"
)</p><p>func main() {
http.HandleFunc("/ping", func(w http.ResponseWriter, r <em>http.Request) {
time.Sleep(10 </em> time.Millisecond) // 模拟处理耗时
w.WriteHeader(http.StatusOK)
w.Write([]byte("pong"))
})</p><pre class="brush:php;toolbar:false;"><code>http.ListenAndServe(":8080", nil)}
运行后,该服务会在 :8080 监听,/ping 接口返回简单响应。
立即学习“go语言免费学习笔记(深入)”;
创建文件 http_benchmark_test.go:
package main
<p>import (
"fmt"
"io"
"net/http"
"sync"
"testing"
)</p><p>const targetURL = "<a href="https://www.php.cn/link/4f9ec8df9f1f7b84f2a3f69c4af72ba9">https://www.php.cn/link/4f9ec8df9f1f7b84f2a3f69c4af72ba9</a>"</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/731">
<img src="https://img.php.cn/upload/ai_manual/001/246/273/68b6d7bb07edf422.png" alt="v0.dev">
</a>
<div class="aritcle_card_info">
<a href="/ai/731">v0.dev</a>
<p>Vercel推出的AI生成式UI工具,通过文本描述生成UI组件代码</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="v0.dev">
<span>232</span>
</div>
</div>
<a href="/ai/731" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="v0.dev">
</a>
</div>
<p>func BenchmarkHTTPSingle(b *testing.B) {
for i := 0; i < b.N; i++ {
resp, err := http.Get(targetURL)
if err != nil {
b.Fatal(err)
}
io.ReadAll(resp.Body)
resp.Body.Close()
}
}</p><p>func BenchmarkHTTPConcurrent(b *testing.B) {
var wg sync.WaitGroup
client := &http.Client{}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">b.ResetTimer()
for i := 0; i < b.N; i++ {
wg.Add(1)
go func() {
defer wg.Done()
req, _ := http.NewRequest("GET", targetURL, nil)
resp, err := client.Do(req)
if err != nil {
b.Error(err)
return
}
io.ReadAll(resp.Body)
resp.Body.Close()
}()
// 控制并发请求数,避免系统资源耗尽
if i%100 == 0 {
wg.Wait()
}
}
wg.Wait()}
说明:
执行命令:
go test -bench=BenchmarkHTTP -run=^$ -benchtime=3s
输出示例:
BenchmarkHTTPSingle 1000000 3000 ns/op BenchmarkHTTPConcurrent 500000 7000 ns/op
注意:
基本上就这些。Golang 的并发模型让 HTTP 性能测试变得简洁高效,合理设计基准测试能帮你发现服务瓶颈,验证优化效果。
以上就是如何用 Golang 测试网络请求性能_Golang HTTP 并发基准测试实例的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号