Files
core/test/performance/http_server_client.go
T
2026-11-27 06:03:56 +00:00

91 lines
2.6 KiB
Go

// 压测客户端只使用 Go 标准库,逐条核对响应,避免驱动成为服务端吞吐上限。
package main
import (
"bytes"
"encoding/json"
"fmt"
"math"
"net/http"
"os"
"slices"
"strconv"
"strings"
"sync"
"time"
)
const concurrency = 32
func run(client *http.Client, url string, api bool, count int, samples []float64) time.Duration {
var workers sync.WaitGroup
started := time.Now()
for lane := range concurrency {
workers.Go(func() {
var received bytes.Buffer
for i := lane; i < count; i += concurrency {
text := strings.Repeat(strconv.Itoa(i), 8)
body, expected := text, text
if api {
body = "{\"value\":\"" + text + "\"}"
expected = "{\"code\":0,\"message\":\"ok\",\"data\":\"" + text + "\"}"
}
begin := time.Now()
request, err := http.NewRequest(http.MethodPost, url, strings.NewReader(body))
if err != nil {
panic(err)
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("User-Agent", "")
response, err := client.Do(request)
if err != nil {
panic(err)
}
received.Reset()
_, err = received.ReadFrom(response.Body)
response.Body.Close()
if err != nil {
panic(err)
}
if response.StatusCode != http.StatusOK || received.String() != expected {
panic(fmt.Sprintf("request %d: %s %q", i, response.Status, received.Bytes()))
}
if samples != nil {
samples[i] = float64(time.Since(begin)) / float64(time.Millisecond)
}
}
})
}
workers.Wait()
return time.Since(started)
}
func main() {
port, countText, api := os.Args[1], os.Args[2], os.Args[3] == "api"
count, err := strconv.Atoi(countText)
if err != nil || count < 1 {
panic("request count must be positive")
}
path := "/echo"
if api {
path = "/benchmark/echo/front/main/echo"
}
url := "http://127.0.0.1:" + port + path
transport := &http.Transport{
MaxConnsPerHost: concurrency, MaxIdleConnsPerHost: concurrency, DisableCompression: true,
}
defer transport.CloseIdleConnections()
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
run(client, url, api, 1024, nil)
samples := make([]float64, count)
seconds := run(client, url, api, count, samples).Seconds()
slices.Sort(samples)
percentile := func(p float64) float64 { return samples[int(math.Ceil(p*float64(count)))-1] }
if err := json.NewEncoder(os.Stdout).Encode(map[string]float64{
"count": float64(count), "seconds": seconds, "requests_per_second": float64(count) / seconds,
"p50_ms": percentile(.50), "p95_ms": percentile(.95), "p99_ms": percentile(.99),
}); err != nil {
panic(err)
}
}