"""Offline Redis 8 lab for Ch 16 (scripting): EVAL/EVALSHA/SCRIPT LOAD/EXISTS/FLUSH/KILL."""
import hashlib
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():
cached_lua = "return {KEYS[1], ARGV[1]}"
expected_sha = hashlib.sha1(cached_lua.encode("utf-8")).hexdigest()
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-cli --raw EVAL "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1 key2 first second
echo "===CASE2==="
redis-cli --raw EVAL "redis.call('SET', KEYS[1], ARGV[1]); return redis.call('INCRBY', KEYS[1], ARGV[2])" 1 counter:lua 10 5
redis-cli --raw GET counter:lua
echo "===CASE3_LOAD==="
SHA=$(redis-cli --raw SCRIPT LOAD "return {KEYS[1], ARGV[1]}")
echo "$SHA"
echo "===CASE3_EXISTS_BEFORE==="
redis-cli --raw SCRIPT EXISTS "$SHA" "0000000000000000000000000000000000000000"
echo "===CASE3_EVALSHA==="
redis-cli --raw EVALSHA "$SHA" 1 user:1 active
echo "===CASE3_FLUSH==="
redis-cli --raw SCRIPT FLUSH
echo "===CASE3_EXISTS_AFTER==="
redis-cli --raw SCRIPT EXISTS "$SHA"
echo "===CASE4==="
redis-cli --raw SCRIPT KILL 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)
c1_actual = sections["CASE1"]
c1_expected = ["key1", "key2", "first", "second"]
c2_actual = sections["CASE2"]
c2_expected = ["15", "15"]
loaded_sha = sections["CASE3_LOAD"][0] if sections["CASE3_LOAD"] else ""
c3_actual = {
"sha_matches": loaded_sha == expected_sha,
"exists_before": sections["CASE3_EXISTS_BEFORE"],
"evalsha_result": sections["CASE3_EVALSHA"],
"flush_reply": sections["CASE3_FLUSH"][0] if sections["CASE3_FLUSH"] else "",
"exists_after": sections["CASE3_EXISTS_AFTER"],
}
c3_expected = {
"sha_matches": True,
"exists_before": ["1", "0"],
"evalsha_result": ["user:1", "active"],
"flush_reply": "OK",
"exists_after": ["0"],
}
c4_msg = " ".join(sections["CASE4"]).strip()
c4_actual = {"notbusy_reported": "NOTBUSY" in c4_msg}
c4_expected = {"notbusy_reported": True}
cases = [
dict(
name="eval_keys_argv_echo",
summary="EVAL 按 numkeys 拆分 KEYS 与 ARGV 并返回 Lua 表结果",
expected=c1_expected,
actual=c1_actual,
passed=(c1_actual == c1_expected),
),
dict(
name="eval_atomic_redis_call",
summary="Lua 脚本通过 redis.call 原子组合 SET 与 INCRBY",
expected=c2_expected,
actual=c2_actual,
passed=(c2_actual == c2_expected),
),
dict(
name="script_load_exists_evalsha_flush",
summary="SCRIPT LOAD 缓存脚本、SCRIPT EXISTS 校验、EVALSHA 执行并 SCRIPT FLUSH 清空",
expected=c3_expected,
actual=c3_actual,
passed=(c3_actual == c3_expected),
),
dict(
name="script_kill_idle_behavior",
summary="空闲状态调用 SCRIPT KILL 返回 NOTBUSY 提示",
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-scripting-lab/explore-scripting.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-scripting.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a1778.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1798.zip