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

离线实测 redis-server 默认/自定义配置启动与 redis-cli 连通读写验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-install.py
explore-install.py149 行
"""Offline verification lab for Redis Ch03: install."""
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
# 1. Start default port 6379 server
redis-server --daemonize yes --save '' --appendonly no >/dev/null
# 2. Start second instance using an explicit config file on port 6380
cat <<'EOF' > /tmp/custom-redis.conf
port 6380
bind 127.0.0.1
daemonize yes
save ""
appendonly no
EOF
redis-server /tmp/custom-redis.conf >/dev/null

i=0
while [ $i -lt 50 ]; do
  P1=$(redis-cli -h 127.0.0.1 -p 6379 --raw PING 2>/dev/null || true)
  P2=$(redis-cli -h 127.0.0.1 -p 6380 --raw PING 2>/dev/null || true)
  if [ "$P1" = "PONG" ] && [ "$P2" = "PONG" ]; then
    break
  fi
  sleep 0.05
  i=$((i + 1))
done

PING_DEFAULT=$(redis-cli -h 127.0.0.1 -p 6379 --raw PING)
PING_CUSTOM=$(redis-cli -h 127.0.0.1 -p 6380 --raw PING)
PORT_CUSTOM=$(redis-cli -h 127.0.0.1 -p 6380 --raw CONFIG GET port | tail -n 1)

# 3. Reproduce chapter SET/GET verification commands
S1=$(redis-cli -h 127.0.0.1 -p 6379 --raw SET myKey abc)
G1=$(redis-cli -h 127.0.0.1 -p 6379 --raw GET myKey)
S2=$(redis-cli -h 127.0.0.1 -p 6380 --raw SET foo bar)
G2=$(redis-cli -h 127.0.0.1 -p 6380 --raw GET foo)

# 4. Inspect redis-server and redis-cli binary availability & help flags
HAS_SERVER=$(command -v redis-server >/dev/null && echo yes || echo no)
HAS_CLI=$(command -v redis-cli >/dev/null && echo yes || echo no)
CLI_HELP_HP=$(redis-cli --help 2>&1 | grep -cE -- '-h <hostname>|-p <port>')
SRV_HELP_CONF=$(redis-server --help 2>&1 | grep -c 'redis.conf')

printf 'PING_DEFAULT=%s\n' "$PING_DEFAULT"
printf 'PING_CUSTOM=%s\n' "$PING_CUSTOM"
printf 'PORT_CUSTOM=%s\n' "$PORT_CUSTOM"
printf 'KV1=%s|%s\n' "$S1" "$G1"
printf 'KV2=%s|%s\n' "$S2" "$G2"
printf 'BINS=%s|%s\n' "$HAS_SERVER" "$HAS_CLI"
printf 'HELP=%s|%s\n' "$CLI_HELP_HP" "$SRV_HELP_CONF"
"""
    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()

    help_parts = [int(x) for x in kv.get("HELP", "0|0").split("|")]

    cases = []

    # Case 1
    actual_1 = {
        "default_6379_ping": kv.get("PING_DEFAULT"),
        "custom_conf_6380_ping": kv.get("PING_CUSTOM"),
        "custom_conf_port": kv.get("PORT_CUSTOM"),
    }
    expected_1 = {
        "default_6379_ping": "PONG",
        "custom_conf_6380_ping": "PONG",
        "custom_conf_port": "6380",
    }
    cases.append({
        "name": "server_default_and_custom_conf_startup",
        "summary": "Start redis-server with default settings (6379) and an explicit redis.conf file (6380), then verify PING.",
        "expected": expected_1,
        "actual": actual_1,
        "passed": actual_1 == expected_1,
    })

    # Case 2
    actual_2 = {
        "myKey_set_get": kv.get("KV1"),
        "foo_set_get": kv.get("KV2"),
    }
    expected_2 = {
        "myKey_set_get": "OK|abc",
        "foo_set_get": "OK|bar",
    }
    cases.append({
        "name": "cli_set_get_verification",
        "summary": "Run redis-cli SET/GET verification sequences (myKey=abc and foo=bar) on running Redis 8 instances.",
        "expected": expected_2,
        "actual": actual_2,
        "passed": actual_2 == expected_2,
    })

    # Case 3
    actual_3 = {
        "binaries_present": kv.get("BINS"),
        "cli_has_host_port_flags": help_parts[0] >= 2,
        "server_mentions_conf": help_parts[1] >= 1,
    }
    expected_3 = {
        "binaries_present": "yes|yes",
        "cli_has_host_port_flags": True,
        "server_mentions_conf": True,
    }
    cases.append({
        "name": "install_cli_and_source_build_syntax",
        "summary": "Verify redis-server and redis-cli executables and CLI options (-h, -p, redis.conf) match installation docs.",
        "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-install-lab/explore-install.py

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

下载课程关联工程包:Redis

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

下载课程关联工程包:Redis

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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