feat: Python(Locust) + Go(boomer) 混合压测框架(演示版)

This commit is contained in:
WbiubiuW
2026-09-22 21:35:03 +08:00
commit 26cdd4b5c1
63 changed files with 6171 additions and 0 deletions
+96
View File
@@ -0,0 +1,96 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"time"
)
// newTunedTransport 返回调优后的 Transport。
// 注意:调优参数必须落在**真正被 client 引用**的那个 Transport 上 —— 若参数
// 写在一个从未被使用的变量上,默认 MaxIdleConnsPerHost=2 会让压测根本压不上去,
// 而且**不报任何错**,最难查。因此本文件配套 TestTransportPool,
// 断言「client 实际使用的 transport 就是调优过的那个」。
func newTunedTransport() *http.Transport {
return &http.Transport{
DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 2000,
MaxIdleConnsPerHost: 1000,
MaxConnsPerHost: 1000,
IdleConnTimeout: 60 * time.Second,
}
}
// APIClient 是被测 mock 网关的 HTTP 客户端。
type APIClient struct {
base string
hc *http.Client
}
func NewAPIClient(base string) *APIClient {
return &APIClient{
base: base,
hc: &http.Client{
Transport: newTunedTransport(), // ← 调优对象就在这里被引用
Timeout: 10 * time.Second,
},
}
}
// Transport 暴露 client 实际使用的 transport(供断言测试用)。
func (c *APIClient) Transport() *http.Transport {
return c.hc.Transport.(*http.Transport)
}
type apiResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data json.RawMessage `json:"data"`
}
// do 发起请求并返回 (httpStatus, bizCode, err)。latency 由调用方统计。
func (c *APIClient) do(method, path string, body any) (int, int, error) {
var reader io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
return 0, -1, err
}
reader = bytes.NewReader(raw)
}
req, err := http.NewRequest(method, c.base+path, reader)
if err != nil {
return 0, -1, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.hc.Do(req)
if err != nil {
return 0, -1, err
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
return resp.StatusCode, -1, err
}
var ar apiResponse
if err := json.Unmarshal(raw, &ar); err != nil {
return resp.StatusCode, -1, fmt.Errorf("decode: %w", err)
}
return resp.StatusCode, ar.Code, nil
}
func (c *APIClient) OpenOrder(path string, p OrderPayload) (int, int, error) {
return c.do(http.MethodPost, path, p)
}
func (c *APIClient) BatchCancel(userID int, orderIDs []int64) (int, int, error) {
return c.do(http.MethodDelete, "/api/v1/order/batch/cancel",
map[string]any{"user_id": userID, "order_ids": orderIDs})
}