"""Offline verification lab for Redis Ch14: pub-sub."""
import json
import shutil
import subprocess
DOCKER_BIN = shutil.which("docker") or r"C:\Program Files\Docker\Docker\resources\bin\docker.exe"
VERSION_LABEL = "CPython 3.12.14 / offline Docker redis:8-alpine (--network none)"
def run_in_redis(script: str, timeout: int = 45) -> subprocess.CompletedProcess:
proc = subprocess.run(
[DOCKER_BIN, "run", "--rm", "-i", "--network", "none", "redis:8-alpine", "sh", "-s"],
input=script.replace("\r\n", "\n").encode("utf-8"),
capture_output=True,
timeout=timeout,
)
return subprocess.CompletedProcess(
proc.args,
proc.returncode,
proc.stdout.decode("utf-8", errors="replace"),
proc.stderr.decode("utf-8", errors="replace"),
)
def main() -> None:
shell = r"""
set -eu
redis-server --daemonize yes --save '' --appendonly no >/dev/null
i=0
while [ $i -lt 50 ]; do
if [ "$(redis-cli --raw PING 2>/dev/null || true)" = "PONG" ]; then
break
fi
sleep 0.05
i=$((i + 1))
done
# 1. Exact channel SUBSCRIBE + PUBLISH deterministic capture
redis-cli --csv SUBSCRIBE demoChat > /tmp/sub1.out 2>/dev/null &
SUB1_PID=$!
i=0
while [ $i -lt 60 ]; do
CNT=$(redis-cli --raw PUBSUB NUMSUB demoChat | tail -n 1)
if [ "$CNT" = "1" ]; then
break
fi
sleep 0.05
i=$((i + 1))
done
PUB1_R1=$(redis-cli --raw PUBLISH demoChat "Redis PUBLISH test")
PUB1_R2=$(redis-cli --raw PUBLISH demoChat "Hello Redis Pub/Sub")
# Wait until output file flushes both messages
i=0
while [ $i -lt 40 ]; do
if [ "$(wc -l < /tmp/sub1.out | tr -d ' ')" -ge 3 ]; then
break
fi
sleep 0.05
i=$((i + 1))
done
kill "$SUB1_PID" 2>/dev/null || true
wait "$SUB1_PID" 2>/dev/null || true
# 2. Pattern PSUBSCRIBE + PUBSUB introspection + PUBLISH
redis-cli --csv PSUBSCRIBE 'news.*' > /tmp/sub2.out 2>/dev/null &
SUB2_PID=$!
i=0
while [ $i -lt 60 ]; do
PAT_CNT=$(redis-cli --raw PUBSUB NUMPAT)
if [ "$PAT_CNT" = "1" ]; then
break
fi
sleep 0.05
i=$((i + 1))
done
NUMPAT_VAL=$(redis-cli --raw PUBSUB NUMPAT)
PUB2_R1=$(redis-cli --raw PUBLISH news.tech "release-8")
i=0
while [ $i -lt 40 ]; do
if [ "$(wc -l < /tmp/sub2.out | tr -d ' ')" -ge 2 ]; then
break
fi
sleep 0.05
i=$((i + 1))
done
kill "$SUB2_PID" 2>/dev/null || true
wait "$SUB2_PID" 2>/dev/null || true
# 3. UNSUBSCRIBE and PUNSUBSCRIBE via RESP over loopback nc
printf 'SUBSCRIBE chA\r\nUNSUBSCRIBE chA\r\nPSUBSCRIBE p.*\r\nPUNSUBSCRIBE p.*\r\nQUIT\r\n' | nc 127.0.0.1 6379 | tr -d '\r' > /tmp/unsub.out
printf 'PUB1=%s|%s\n' "$PUB1_R1" "$PUB1_R2"
printf 'SUB1_LINES=%s\n' "$(tr '\n' ';' < /tmp/sub1.out)"
printf 'PUB2=%s|%s\n' "$NUMPAT_VAL" "$PUB2_R1"
printf 'SUB2_LINES=%s\n' "$(tr '\n' ';' < /tmp/sub2.out)"
printf 'UNSUB_HAS_UNSUB=%s\n' "$(grep -c '^unsubscribe$' /tmp/unsub.out)"
printf 'UNSUB_HAS_PUNSUB=%s\n' "$(grep -c '^punsubscribe$' /tmp/unsub.out)"
"""
proc = run_in_redis(shell)
if proc.returncode != 0:
raise RuntimeError(f"Redis container failed: {proc.stderr}")
kv = {}
for line in proc.stdout.splitlines():
if "=" in line:
k, v = line.split("=", 1)
kv[k.strip()] = v.strip()
sub1_lines = [ln for ln in kv.get("SUB1_LINES", "").split(";") if ln]
sub2_lines = [ln for ln in kv.get("SUB2_LINES", "").split(";") if ln]
cases = []
# Case 1
actual_1 = {
"publish_receiver_counts": kv.get("PUB1"),
"subscriber_frames": sub1_lines,
}
expected_1 = {
"publish_receiver_counts": "1|1",
"subscriber_frames": [
'"subscribe","demoChat",1',
'"message","demoChat","Redis PUBLISH test"',
'"message","demoChat","Hello Redis Pub/Sub"',
],
}
cases.append({
"name": "pubsub_subscribe_publish_delivery",
"summary": "Subscribe to demoChat in a background client, publish two messages, and verify exact delivery frames.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2
actual_2 = {
"numpat_and_receivers": kv.get("PUB2"),
"pattern_frames": sub2_lines,
}
expected_2 = {
"numpat_and_receivers": "1|1",
"pattern_frames": [
'"psubscribe","news.*",1',
'"pmessage","news.*","news.tech","release-8"',
],
}
cases.append({
"name": "pubsub_pattern_subscribe_and_introspect",
"summary": "Verify PSUBSCRIBE news.*, PUBSUB NUMPAT introspection, and pmessage delivery on PUBLISH news.tech.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3
actual_3 = {
"unsubscribe_frame_received": kv.get("UNSUB_HAS_UNSUB") == "1",
"punsubscribe_frame_received": kv.get("UNSUB_HAS_PUNSUB") == "1",
}
expected_3 = {
"unsubscribe_frame_received": True,
"punsubscribe_frame_received": True,
}
cases.append({
"name": "pubsub_unsubscribe_and_punsubscribe",
"summary": "Verify UNSUBSCRIBE and PUNSUBSCRIBE protocol responses over a local Redis 8 loopback session.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
print(json.dumps({"version": VERSION_LABEL, "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-pub-sub-lab/explore-pub-sub.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-pub-sub.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1797.zip
课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a1778.zip