"""Offline Redis 8 lab for Ch 23 (benchmarks): redis-benchmark CLI flags, -q, -t, -P, --csv."""
import csv
import io
import json
import re
import subprocess
VERSION = "CPython 3.12.14 / offline Docker redis:8-alpine (--network none)"
def run_in_redis(shell_script: str) -> str:
proc = subprocess.run(
["docker", "run", "--rm", "--network", "none", "redis:8-alpine", "sh", "-c", shell_script],
capture_output=True,
encoding="utf-8",
check=True,
timeout=60,
)
return proc.stdout
def parse_quiet_lines(lines):
parsed = {}
for line in lines:
m = re.match(r"^([^:]+):\s+([0-9.]+)\s+requests per second", line.strip())
if m:
parsed[m.group(1).strip()] = float(m.group(2))
return parsed
def main():
script = r"""
set -e
redis-server --daemonize yes --save '' --appendonly no --dir /tmp
until redis-cli PING >/dev/null 2>&1; do sleep 0.05; done
echo "===CASE1==="
redis-benchmark -h 127.0.0.1 -p 6379 -n 200 -c 4 -t ping,set,get -q
echo "===CASE2==="
redis-benchmark -h 127.0.0.1 -p 6379 -t set,lpush -n 200 -c 4 -d 32 -r 100 -q
echo "===CASE3==="
redis-benchmark -h 127.0.0.1 -p 6379 -t set,get -n 2000 -c 4 -P 8 --csv
echo "===CASE4==="
redis-benchmark --help 2>&1 || true
"""
raw = run_in_redis(script).replace("\r\n", "\n")
sections = {}
cur = None
for line in raw.splitlines():
if line.startswith("===") and line.endswith("==="):
cur = line.strip("=")
sections[cur] = []
elif cur is not None:
sections[cur].append(line)
p1 = parse_quiet_lines(sections["CASE1"])
c1_actual = {
"commands_present": sorted(p1.keys()),
"all_rps_positive": bool(p1) and all(v > 0 for v in p1.values()),
}
c1_expected = {
"commands_present": ["GET", "PING_INLINE", "PING_MBULK", "SET"],
"all_rps_positive": True,
}
p2 = parse_quiet_lines(sections["CASE2"])
c2_actual = {
"commands_present": sorted(p2.keys()),
"all_rps_positive": bool(p2) and all(v > 0 for v in p2.values()),
}
c2_expected = {
"commands_present": ["LPUSH", "SET"],
"all_rps_positive": True,
}
csv_rows = list(csv.reader(io.StringIO("\n".join(sections["CASE3"]))))
csv_data = {r[0]: float(r[1]) for r in csv_rows[1:] if len(r) >= 2}
c3_actual = {
"header_has_test_and_rps": len(csv_rows) >= 3 and csv_rows[0][0] == "test" and csv_rows[0][1] == "rps",
"commands": sorted(csv_data.keys()),
"all_rps_positive": bool(csv_data) and all(v > 0 for v in csv_data.values()),
}
c3_expected = {
"header_has_test_and_rps": True,
"commands": ["GET", "SET"],
"all_rps_positive": True,
}
help_text = "\n".join(sections["CASE4"])
flags = ["-h", "-p", "-s", "-c", "-n", "-d", "-k", "-r", "-P", "-q", "--csv", "-l", "-t", "-I"]
c4_actual = {"all_14_flags_present": all(f in help_text for f in flags), "flag_count": sum(1 for f in flags if f in help_text)}
c4_expected = {"all_14_flags_present": True, "flag_count": 14}
cases = [
dict(
name="benchmark_ping_set_get_quiet",
summary="redis-benchmark -n 200 -c 4 -t ping,set,get -q 实测输出 4 项正吞吐率",
expected=c1_expected,
actual=c1_actual,
passed=(c1_actual == c1_expected),
),
dict(
name="benchmark_set_lpush_custom_payload",
summary="组合 -h/-p/-t/-n/-c/-d/-r/-q 压测 set 与 lpush 命令",
expected=c2_expected,
actual=c2_actual,
passed=(c2_actual == c2_expected),
),
dict(
name="benchmark_pipeline_and_csv",
summary="使用 -P 8 管道与 --csv 输出结构化基准报告",
expected=c3_expected,
actual=c3_actual,
passed=(c3_actual == c3_expected),
),
dict(
name="benchmark_cli_help_flags",
summary="核验 Redis 8 redis-benchmark --help 支持表列全部 14 项参数",
expected=c4_expected,
actual=c4_actual,
passed=(c4_actual == c4_expected),
),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/redis-benchmarks-lab/explore-benchmarks.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-benchmarks.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1780.zip
课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a1778.zip