用 Go 快速写一个 HTTP 压测工具
【摘要】 不需要 wrk、不需要 ab,几十行 Go 代码,就能拥有一个可控的压测工具。
一、核心思路
压测工具的本质很简单:
-
控制并发数(goroutine 池)
-
控制总量或时长
-
统计结果(QPS、成功率、延迟)
结构如下:
main
├─ 启动 N 个 worker(goroutine)
├─ 每个 worker 发 M 个请求
├─ 结果写入 channel
└─ 主线程汇总统计
二、最小可用版(~60 行)
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
func main() {
url := "http://127.0.0.1:8080"
concurrency := 50
total := 1000
perWorker := total / concurrency
results := make(chan time.Duration, total)
var wg sync.WaitGroup
start := time.Now()
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func() {
defer wg.Done()
client := http.Client{Timeout: 10 * time.Second}
for j := 0; j < perWorker; j++ {
t := time.Now()
resp, err := client.Get(url)
if err == nil {
resp.Body.Close()
}
results <- time.Since(t)
}
}()
}
wg.Wait()
close(results)
var count int
var totalLatency time.Duration
for d := range results {
count++
totalLatency += d
}
fmt.Printf("请求数: %d\n", count)
fmt.Printf("QPS: %.2f\n", float64(count)/time.Since(start).Seconds())
fmt.Printf("平均耗时: %v\n", totalLatency/time.Duration(count))
}
运行:
go run main.go
输出示例:
请求数: 1000
QPS: 4123.56
平均耗时: 12.34ms
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)