sky/scripts/loadtest.py
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

157 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
并发压测:验证「CDN → 缓存 → DB」三级拦截中缓存层的实际效果。
重点验证三件事:
1. 热点 key 过期瞬间,singleflight 是否把并发回源合并成 1 次
2. 缓存命中下 QPS 与 P99
3. 写路径(点赞)是否能扛住高并发而不打崩数据库
"""
import concurrent.futures as cf
import json
import statistics
import sys
import time
import urllib.request
import urllib.error
API = "http://127.0.0.1:18080"
def get(path):
req = urllib.request.Request(API + path)
t0 = time.perf_counter()
try:
with urllib.request.urlopen(req, timeout=20) as r:
r.read()
return (time.perf_counter() - t0) * 1000, r.status
except urllib.error.HTTPError as e:
e.read()
return (time.perf_counter() - t0) * 1000, e.code
except Exception:
return (time.perf_counter() - t0) * 1000, 0
def post(path, body, token):
data = json.dumps(body, ensure_ascii=False).encode()
req = urllib.request.Request(API + path, data=data, method="POST")
req.add_header("Content-Type", "application/json; charset=utf-8")
req.add_header("Authorization", "Bearer " + token)
t0 = time.perf_counter()
try:
with urllib.request.urlopen(req, timeout=20) as r:
r.read()
return (time.perf_counter() - t0) * 1000, r.status
except urllib.error.HTTPError as e:
e.read()
return (time.perf_counter() - t0) * 1000, e.code
except Exception:
return (time.perf_counter() - t0) * 1000, 0
def stat(name, lat, conc, wall):
lat.sort()
p50 = lat[len(lat) // 2]
p95 = lat[int(len(lat) * 0.95)]
p99 = lat[int(len(lat) * 0.99)]
qps = len(lat) / (wall / 1000)
print(f" {name}")
print(f" 请求数 {len(lat)} 并发 {conc} 墙钟 {wall/1000:.2f}s")
print(f" QPS {qps:>8.0f} P50 {p50:>6.1f}ms P95 {p95:>6.1f}ms P99 {p99:>6.1f}ms")
return qps, p99
def main():
# 找一个已发布文章
with urllib.request.urlopen(API + "/api/v1/articles?limit=1", timeout=10) as r:
items = json.load(r)["data"]["items"]
if not items:
print("没有已发布文章,先跑 smoke.py")
sys.exit(1)
mask = items[0]["mask_id"]
print(f"目标文章: {mask}\n")
# 登录拿 token(用于写路径测试)
body = json.dumps({"account": "perfuser01", "password": "PerfPass123!"}).encode()
req = urllib.request.Request(API + "/api/v1/auth/register", data=body, method="POST")
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req, timeout=10) as r:
token = json.load(r)["data"]["token"]
except urllib.error.HTTPError:
req = urllib.request.Request(API + "/api/v1/auth/login", data=body, method="POST")
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, timeout=10) as r:
token = json.load(r)["data"]["token"]
print("═" * 56)
print(" 一、读路径(缓存命中)")
print("═" * 56)
for conc in (32, 128, 256):
n = conc * 40
t0 = time.perf_counter()
with cf.ThreadPoolExecutor(max_workers=conc) as ex:
res = list(ex.map(lambda _: get(f"/api/v1/articles/{mask}"), range(n)))
wall = (time.perf_counter() - t0) * 1000
lat = [x[0] for x in res]
codes = {}
for _, c in res:
codes[c] = codes.get(c, 0) + 1
qps, p99 = stat(f"读文章 ×{n}", lat, conc, wall)
bad_codes = {k: v for k, v in codes.items() if k != 200}
if bad_codes:
print(f" \033[31m异常状态码: {bad_codes}\033[0m")
else:
print(f" \033[32m全部 200\033[0m")
print()
print("═" * 56)
print(" 二、写路径(点赞,Valkey 计数)")
print("═" * 56)
for conc in (32, 128):
n = conc * 20
t0 = time.perf_counter()
with cf.ThreadPoolExecutor(max_workers=conc) as ex:
res = list(ex.map(
lambda _: post(f"/api/v1/articles/{mask}/like", {}, token), range(n)))
wall = (time.perf_counter() - t0) * 1000
lat = [x[0] for x in res]
codes = {}
for _, c in res:
codes[c] = codes.get(c, 0) + 1
stat(f"点赞 ×{n}", lat, conc, wall)
print(f" 状态码分布 {codes}")
print()
print("═" * 56)
print(" 三、冷缓存(singleflight 验证)")
print("═" * 56)
# 找一个冷文章(未缓存过的 mask)
other = items[-1]["mask_id"] if len(items) > 1 else mask
print(f" 目标: {other}(模拟缓存失效瞬间的并发回源)")
conc = 200
n = 400
t0 = time.perf_counter()
with cf.ThreadPoolExecutor(max_workers=conc) as ex:
res = list(ex.map(lambda _: get(f"/api/v1/articles/{other}"), range(n)))
wall = (time.perf_counter() - t0) * 1000
lat = [x[0] for x in res]
codes = {}
for _, c in res:
codes[c] = codes.get(c, 0) + 1
stat(f"冷读 ×{n}", lat, conc, wall)
print(f" 状态码分布 {codes}")
print()
print("═" * 56)
print(" 四、健康检查")
print("═" * 56)
for p in ("/healthz", "/readyz"):
ms, code = get(p)
print(f" {p:12s} {code} {ms:.1f}ms")
if __name__ == "__main__":
main()