蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 Redis 8 原始管道、redis-cli --pipe、FIFO 批处理与 -P 1/-P 16 吞吐对比实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-pipelining.py
explore-pipelining.py130 行
"""Offline Redis 8 lab for Ch 25 (pipelining): raw inline pipeline, redis-cli --pipe, RESP batch, throughput."""
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 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==="
printf 'PING\r\nSET demokey redis\r\nGET demokey\r\nINCR visitor\r\nINCR visitor\r\nINCR visitor\r\nQUIT\r\n' | nc 127.0.0.1 6379

echo "===CASE2_PIPE==="
printf '*3\r\n$3\r\nSET\r\n$7\r\npipe:k1\r\n$2\r\nv1\r\n*3\r\n$3\r\nSET\r\n$7\r\npipe:k2\r\n$2\r\nv2\r\n*3\r\n$3\r\nSET\r\n$7\r\npipe:k3\r\n$2\r\nv3\r\n*3\r\n$3\r\nSET\r\n$7\r\npipe:k4\r\n$2\r\nv4\r\n*3\r\n$3\r\nSET\r\n$7\r\npipe:k5\r\n$2\r\nv5\r\n' | redis-cli --pipe 2>&1
echo "===CASE2_MGET==="
redis-cli --raw MGET pipe:k1 pipe:k2 pipe:k3 pipe:k4 pipe:k5

echo "===CASE3==="
{
  i=1
  while [ $i -le 10 ]; do
    printf '*2\r\n$4\r\nINCR\r\n$9\r\nbatch_seq\r\n'
    i=$((i + 1))
  done
  printf '*1\r\n$4\r\nQUIT\r\n'
} | nc 127.0.0.1 6379

echo "===CASE4_SEQ==="
redis-benchmark -n 2000 -c 1 -t ping -P 1 -q
echo "===CASE4_PIPE==="
redis-benchmark -n 2000 -c 1 -t ping -P 16 -q
"""
    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)

    c1_actual = sections["CASE1"]
    c1_expected = ["+PONG", "+OK", "$5", "redis", ":1", ":2", ":3", "+OK"]

    pipe_out = "\n".join(sections["CASE2_PIPE"])
    c2_actual = {
        "zero_errors_five_replies": ("errors: 0, replies: 5" in pipe_out),
        "values": sections["CASE2_MGET"],
    }
    c2_expected = {
        "zero_errors_five_replies": True,
        "values": ["v1", "v2", "v3", "v4", "v5"],
    }

    c3_actual = sections["CASE3"]
    c3_expected = [f":{i}" for i in range(1, 11)] + ["+OK"]

    def extract_ping_rps(lines):
        for l in lines:
            m = re.search(r"PING_INLINE:\s+([0-9.]+)\s+requests per second", l)
            if m:
                return float(m.group(1))
        return 0.0

    seq_rps = extract_ping_rps(sections["CASE4_SEQ"])
    pipe_rps = extract_ping_rps(sections["CASE4_PIPE"])
    c4_actual = {
        "seq_rps_positive": seq_rps > 0,
        "pipe_rps_positive": pipe_rps > 0,
        "pipelined_faster": pipe_rps > seq_rps,
    }
    c4_expected = {
        "seq_rps_positive": True,
        "pipe_rps_positive": True,
        "pipelined_faster": True,
    }

    cases = [
        dict(
            name="raw_inline_pipeline_batch",
            summary="单次 TCP 批量提交 6 条内联命令并一次回收全部 RESP 响应",
            expected=c1_expected,
            actual=c1_actual,
            passed=(c1_actual == c1_expected),
        ),
        dict(
            name="redis_cli_pipe_mass_insert",
            summary="通过 redis-cli --pipe 批量导入 5 组 RESP 键值对(0 错误、5 响应)",
            expected=c2_expected,
            actual=c2_actual,
            passed=(c2_actual == c2_expected),
        ),
        dict(
            name="resp_array_pipeline_fifo",
            summary="一次管道批量发送 10 条 RESP 数组 INCR 命令,响应严格按 FIFO 顺序返回 1..10",
            expected=c3_expected,
            actual=c3_actual,
            passed=(c3_actual == c3_expected),
        ),
        dict(
            name="pipeline_vs_sequential_throughput",
            summary="单连接对比 -P 1 与 -P 16 管道压测,验证管道显著提升吞吐率",
            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-pipelining-lab/explore-pipelining.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-pipelining.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Redis

课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a1778.zip

下载课程关联工程包:Redis

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1796.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习