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

运行离线 Redis 8 范围分片、CRC16 集群哈希槽、双实例跨片限制与一致性哈希实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-partitioning.py
explore-partitioning.py205 行
"""Offline Redis 8 lab for Ch 26 (partitioning): range/hash sharding, CRC16 cluster slots, cross-shard SINTER, consistent hashing."""
import bisect
import hashlib
import json
import subprocess
import zlib

VERSION = "CPython 3.12.14 / offline Docker redis:8-alpine (--network none)"


def crc16_xmodem(data: bytes) -> int:
    crc = 0
    for b in data:
        crc ^= b << 8
        for _ in range(8):
            if crc & 0x8000:
                crc = ((crc << 1) ^ 0x1021) & 0xFFFF
            else:
                crc = (crc << 1) & 0xFFFF
    return crc


def redis_cluster_slot(key: str) -> int:
    s = key.find("{")
    if s != -1:
        e = key.find("}", s + 1)
        if e != -1 and e != s + 1:
            key = key[s + 1 : e]
    return crc16_xmodem(key.encode("utf-8")) % 16384


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 --port 6379 --cluster-enabled yes --cluster-config-file /tmp/nodes.conf
until redis-cli -p 6379 PING >/dev/null 2>&1; do sleep 0.05; done

echo "===CASE2_SLOTS==="
echo "FOOBAR=$(redis-cli -p 6379 --raw CLUSTER KEYSLOT foobar)"
echo "TAG1=$(redis-cli -p 6379 --raw CLUSTER KEYSLOT '{user1000}.following')"
echo "TAG2=$(redis-cli -p 6379 --raw CLUSTER KEYSLOT '{user1000}.followers')"

redis-server --daemonize yes --save '' --appendonly no --dir /tmp --port 6380
until redis-cli -p 6380 PING >/dev/null 2>&1; do sleep 0.05; done
redis-server --daemonize yes --save '' --appendonly no --dir /tmp --port 6381
until redis-cli -p 6381 PING >/dev/null 2>&1; do sleep 0.05; done

echo "===CASE3==="
redis-cli -p 6380 SADD setA redis python >/dev/null
redis-cli -p 6381 SADD setB redis go >/dev/null
echo "CROSS_COUNT=$(redis-cli -p 6380 --raw SINTER setA setB | grep -c . || true)"
redis-cli -p 6380 SADD '{g1}:setA' redis python >/dev/null
redis-cli -p 6380 SADD '{g1}:setB' redis go >/dev/null
echo "COLOCATED=$(redis-cli -p 6380 --raw SINTER '{g1}:setA' '{g1}:setB')"
"""
    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: Range partitioning across 4 instances R0..R3
    def range_shard(uid: int) -> str:
        if uid <= 10000:
            return "R0"
        if uid <= 20000:
            return "R1"
        if uid <= 30000:
            return "R2"
        return "R3"

    c1_actual = {
        "user:1": range_shard(1),
        "user:10000": range_shard(10000),
        "user:10001": range_shard(10001),
        "user:25000": range_shard(25000),
        "user:35000": range_shard(35000),
    }
    c1_expected = {
        "user:1": "R0",
        "user:10000": "R0",
        "user:10001": "R1",
        "user:25000": "R2",
        "user:35000": "R3",
    }

    # Case 2: CRC32 modulo hash partitioning + Redis 8 real CLUSTER KEYSLOT CRC16 verification
    s_map = dict(l.split("=", 1) for l in sections["CASE2_SLOTS"] if "=" in l)
    crc32_foobar = zlib.crc32(b"foobar") & 0xFFFFFFFF
    slot_foobar_redis = int(s_map["FOOBAR"])
    slot_tag1_redis = int(s_map["TAG1"])
    slot_tag2_redis = int(s_map["TAG2"])
    c2_actual = {
        "crc32_mod4_foobar": crc32_foobar % 4,
        "slot_foobar_redis": slot_foobar_redis,
        "slot_foobar_matches_crc16": (slot_foobar_redis == redis_cluster_slot("foobar")),
        "hash_tag_same_slot": (slot_tag1_redis == slot_tag2_redis == redis_cluster_slot("{user1000}.following")),
        "slot_in_0_16383": (0 <= slot_foobar_redis < 16384),
    }
    c2_expected = {
        "crc32_mod4_foobar": crc32_foobar % 4,
        "slot_foobar_redis": 12325,
        "slot_foobar_matches_crc16": True,
        "hash_tag_same_slot": True,
        "slot_in_0_16383": True,
    }

    # Case 3: Cross-shard multi-key SINTER fails across 2 real Redis instances; co-located succeeds
    c3_map = dict(l.split("=", 1) for l in sections["CASE3"] if "=" in l)
    c3_actual = {
        "cross_shard_sinter_count": int(c3_map["CROSS_COUNT"]),
        "colocated_sinter_result": c3_map["COLOCATED"],
    }
    c3_expected = {
        "cross_shard_sinter_count": 0,
        "colocated_sinter_result": "redis",
    }

    # Case 4: Consistent hashing ring vs naive modulo when scaling 4 -> 5 nodes
    keys = [f"item:{i}" for i in range(1000)]
    mod_moved = sum(
        1 for k in keys if (zlib.crc32(k.encode()) % 4) != (zlib.crc32(k.encode()) % 5)
    )

    def build_ring(nodes, vnodes=100):
        ring = []
        owners = {}
        for n in nodes:
            for v in range(vnodes):
                h = int(hashlib.md5(f"{n}#{v}".encode()).hexdigest()[:8], 16)
                ring.append(h)
                owners[h] = n
        ring.sort()
        return ring, owners

    def pick_node(ring, owners, key):
        h = int(hashlib.md5(key.encode()).hexdigest()[:8], 16)
        idx = bisect.bisect_left(ring, h) % len(ring)
        return owners[ring[idx]]

    r4, o4 = build_ring(["R0", "R1", "R2", "R3"])
    r5, o5 = build_ring(["R0", "R1", "R2", "R3", "R4"])
    ch_moved = sum(1 for k in keys if pick_node(r4, o4, k) != pick_node(r5, o5, k))
    c4_actual = {
        "naive_mod_remapped_gt_70pct": mod_moved > 700,
        "consistent_hash_remapped_lt_30pct": ch_moved < 300,
        "consistent_hash_much_less_migration": ch_moved < mod_moved // 2,
    }
    c4_expected = {
        "naive_mod_remapped_gt_70pct": True,
        "consistent_hash_remapped_lt_30pct": True,
        "consistent_hash_much_less_migration": True,
    }

    cases = [
        dict(
            name="range_partitioning_routing",
            summary="按用户 ID 区间将键值路由到 R0..R3 四个分片实例",
            expected=c1_expected,
            actual=c1_actual,
            passed=(c1_actual == c1_expected),
        ),
        dict(
            name="hash_partitioning_and_cluster_slots",
            summary="CRC32 取模哈希分片并与 Redis 8 真实 CLUSTER KEYSLOT (CRC16 mod 16384) 及 Hash Tag 同槽校验一致",
            expected=c2_expected,
            actual=c2_actual,
            passed=(c2_actual == c2_expected),
        ),
        dict(
            name="cross_shard_multi_key_limitation",
            summary="在双实例分片上实测跨实例 SINTER 无法求交,而同实例/同 Hash Tag 键可正常求交",
            expected=c3_expected,
            actual=c3_actual,
            passed=(c3_actual == c3_expected),
        ),
        dict(
            name="consistent_hashing_rebalance_ratio",
            summary="4 节点扩至 5 节点时对比简单取模(>70% 迁移)与一致性哈希虚拟节点环(<30% 迁移)",
            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-partitioning-lab/explore-partitioning.py

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

下载课程关联工程包:Redis

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

下载课程关联工程包:Redis

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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