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

运行离线 Redis 8 事务入队、非回滚行为、DISCARD 与 WATCH 乐观锁实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-transactions.py
explore-transactions.py182 行
"""Offline Redis 8 lab for Ch 15 (transactions): MULTI/EXEC/DISCARD/WATCH/UNWATCH."""
import json
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 'MULTI\r\nSET book-name "Mastering C++ in 21 days"\r\nGET book-name\r\nSADD tag "C++" "Programming" "Mastering Series"\r\nSMEMBERS tag\r\nEXEC\r\nQUIT\r\n' | nc 127.0.0.1 6379

echo "===CASE2A==="
printf 'MULTI\r\nSET a aaa\r\nINCR a\r\nSET c ccc\r\nEXEC\r\nQUIT\r\n' | nc 127.0.0.1 6379
echo "===CASE2A_VALS==="
redis-cli GET a
redis-cli GET c

echo "===CASE2B==="
printf 'MULTI\r\nSET k1 v1\r\nSET k2 v2\r\nSET k3 v3\r\nEXEC\r\nQUIT\r\n' | nc 127.0.0.1 6379

echo "===CASE3==="
redis-cli SET draft-key init >/dev/null
printf 'MULTI\r\nSET draft-key changed\r\nDISCARD\r\nGET draft-key\r\nQUIT\r\n' | nc 127.0.0.1 6379

echo "===CASE4A==="
redis-cli SET balance 100 >/dev/null
{
  printf 'WATCH balance\r\n'
  sleep 0.2
  printf 'MULTI\r\nSET balance 80\r\nEXEC\r\nQUIT\r\n'
} | nc 127.0.0.1 6379 > /tmp/watch_out.txt &
PID=$!
sleep 0.1
redis-cli SET balance 120 >/dev/null
wait $PID
cat /tmp/watch_out.txt
echo "===CASE4A_BAL==="
redis-cli GET balance

echo "===CASE4B==="
{
  printf 'WATCH balance\r\nUNWATCH\r\n'
  sleep 0.2
  printf 'MULTI\r\nSET balance 200\r\nEXEC\r\nQUIT\r\n'
} | nc 127.0.0.1 6379 > /tmp/unwatch_out.txt &
PID2=$!
sleep 0.1
redis-cli SET balance 150 >/dev/null
wait $PID2
cat /tmp/unwatch_out.txt
echo "===CASE4B_BAL==="
redis-cli GET balance
"""
    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)

    # Case 1: MULTI/EXEC batch queue
    c1_lines = sections["CASE1"]
    queued_count = sum(1 for l in c1_lines if l == "+QUEUED")
    tags = sorted(l for l in c1_lines if l in {"C++", "Programming", "Mastering Series"})
    c1_actual = {
        "multi_ok": "+OK" in c1_lines,
        "queued_count": queued_count,
        "book_name": "Mastering C++ in 21 days" if "Mastering C++ in 21 days" in c1_lines else None,
        "sadd_count": 3 if ":3" in c1_lines else 0,
        "tags": tags,
    }
    c1_expected = {
        "multi_ok": True,
        "queued_count": 4,
        "book_name": "Mastering C++ in 21 days",
        "sadd_count": 3,
        "tags": ["C++", "Mastering Series", "Programming"],
    }

    # Case 2: Runtime error does NOT roll back earlier or skip later commands
    c2a_lines = sections["CASE2A"]
    c2a_vals = sections["CASE2A_VALS"]
    c2b_lines = sections["CASE2B"]
    c2_actual = {
        "has_incr_err": any(l.startswith("-ERR") for l in c2a_lines),
        "a_not_rolled_back": c2a_vals[0] if len(c2a_vals) > 0 else "",
        "c_still_executed": c2a_vals[1] if len(c2a_vals) > 1 else "",
        "three_set_batch_ok": c2b_lines.count("+OK") >= 5,  # MULTI + 3 EXEC OKs + QUIT
    }
    c2_expected = {
        "has_incr_err": True,
        "a_not_rolled_back": "aaa",
        "c_still_executed": "ccc",
        "three_set_batch_ok": True,
    }

    # Case 3: DISCARD aborts transaction
    c3_lines = sections["CASE3"]
    c3_actual = {
        "queued": "+QUEUED" in c3_lines,
        "discard_ok": c3_lines.count("+OK") >= 3,  # MULTI + DISCARD + QUIT
        "draft_key_unchanged": "init" in c3_lines,
    }
    c3_expected = {
        "queued": True,
        "discard_ok": True,
        "draft_key_unchanged": True,
    }

    # Case 4: WATCH aborts on concurrent modification; UNWATCH clears lock
    c4a_lines = sections["CASE4A"]
    c4a_bal = sections["CASE4A_BAL"][0] if sections["CASE4A_BAL"] else ""
    c4b_lines = sections["CASE4B"]
    c4b_bal = sections["CASE4B_BAL"][0] if sections["CASE4B_BAL"] else ""
    c4_actual = {
        "watch_aborted_nil_array": "*-1" in c4a_lines,
        "balance_after_abort": c4a_bal,
        "unwatch_exec_succeeded": "*1" in c4b_lines,
        "balance_after_unwatch": c4b_bal,
    }
    c4_expected = {
        "watch_aborted_nil_array": True,
        "balance_after_abort": "120",
        "unwatch_exec_succeeded": True,
        "balance_after_unwatch": "200",
    }

    cases = [
        dict(
            name="multi_exec_batch_queue",
            summary="MULTI 入队 4 条命令并由 EXEC 批量执行返回结果数组",
            expected=c1_expected,
            actual=c1_actual,
            passed=(c1_actual == c1_expected),
        ),
        dict(
            name="partial_runtime_error_no_rollback",
            summary="事务中运行期命令出错不回滚前序命令且继续执行后续命令",
            expected=c2_expected,
            actual=c2_actual,
            passed=(c2_actual == c2_expected),
        ),
        dict(
            name="discard_aborts_queued_commands",
            summary="DISCARD 清空事务队列并保持原键值不变",
            expected=c3_expected,
            actual=c3_actual,
            passed=(c3_actual == c3_expected),
        ),
        dict(
            name="watch_optimistic_lock_and_unwatch",
            summary="WATCH 乐观锁在键被并发修改时中止 EXEC,UNWATCH 解除监视后正常提交",
            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-transactions-lab/explore-transactions.py

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

下载课程关联工程包:Redis

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

下载课程关联工程包:Redis

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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