跳至主要內容
產品桌面工具TASTECAD圖面檢視TASTEFILES檔案管理TASTEFTP檔案傳輸TASTESSH遠端工作空間TASTEZIP壓縮與解壓縮TASTEWINM檔案管理開發工具TASTECODERust 整合開發環境TASTESTUDIO整合開發與測試環境TASTEETL資料整合(ETL)伺服器TASTEREMOTE遠端桌面伺服器TASTEGEO空間資訊伺服器TASTEMAIL郵件工作空間投資TASTESTOCK股票自動交易桌面應用程式開始使用下載文件購買所有產品
市集
資訊
技術資訊今日開發資訊開發文件程式語言RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular伺服器框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express應用程式與桌面框架TauriFlutterReact NativeElectron演算法演算法基礎核心演算法進階演算法實務演算法
社群專案開發日誌提示詞AI 工具問題作品展示社群指南
合作技術傳授網站建置桌面應用程式建置發布與付款流程銷售合作夥伴聯絡我們
服務遠端桌面安裝包客製
TASTEDEV
產品

桌面工具

TASTECAD再複雜的圖面,也能輕鬆開啟TASTEFILES只挑需要的檔案,最快送達TASTEFTP讓檔案往來,走最俐落的路TASTESSH在你與伺服器之間,築起更穩固的連線TASTEZIP壓得更快,解得更安心TASTEWINM以鍵盤為主、用兩個窗格整理檔案的檔案管理器

開發工具

TASTECODE在一個視窗中完成 Rust 應用程式的編輯、建置、偵錯與測試TASTESTUDIO從編輯到遠端測試,再到經核准的 AI 修正TASTEETL邊看數值,邊搬資料

伺服器

TASTEREMOTE在自己的伺服器上運行的遠端桌面TASTEGEO以 Rust 重新打造相容 GeoServer 的空間資訊伺服器TASTEMAIL把郵件的主導權拿回自己手上

投資

TASTESTOCK何時、做什麼——依你訂下的規則運作的股票自動交易

開始使用

下載所有產品的最新版本文件各產品使用方法購買訂閱與永久授權所有產品一覽全部產品
所有產品
市集資訊
技術

資訊

今日開發資訊語言、框架、GitHub 與 AI 官方發布開發文件語言、框架與演算法指南

程式語言

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

框架

Web 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular
伺服器框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express
應用程式與桌面框架TauriFlutterReact NativeElectron

演算法

演算法基礎複雜度分析 · 排序 · 搜尋 · 基礎資料結構 · 樹與堆積核心演算法圖形走訪 · 最短路徑與最小生成樹 · 動態規劃 · 貪婪演算法 · 分治法 · 回溯法進階演算法字串演算法 · 數學與數論 · 位元運算 · 線段樹 · 併查集實務演算法程式面試解題策略 · LRU 快取 · 速率限制 · 一致性雜湊
查看全部開發文件
社群
專案探索開發者與作品開發日誌決策與試錯提示詞可重複使用的指令AI 工具問題Claude、Codex、Gemini 的問題與替代做法作品展示已完成的成果社群指南我們如何公開打造
合作
技術傳授用 Rust 與 egui 打造原生應用程式網站建置10 種語言、帳號、文件與下載桌面應用程式建置Rust 與 egui,不用 WebView發布與付款流程簽章、MSI、deb、rpm、AppImage、雜湊銷售合作夥伴推薦即得 30%聯絡我們開發、合作與投資諮詢
服務
遠端桌面用瀏覽器連線你的電腦安裝包客製只裝需要的,設定預先放好
購買
繁
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
登入
登入
TASTEDEV

從小工具到更好的開發。

support@tastedev.net支持 TASTEDEV
產品產品系列購買文件下載市集客戶支援
社群專案開發日誌提示詞AI 工具問題作品展示
政策關於我們隱私權政策服務條款訂閱條款退款政策社群規範
帳戶登入註冊
訪客
今天
昨天
累計瀏覽
公司名稱
GXSOFT
負責人
CHOI YOUNG GU
營業登記號碼
853-44-00368
地址
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
電子郵件
whitecalvin@tastedev.net
個人資料保護負責人
CHOI YOUNG GU

© 2026 TASTEDEV產品資訊以經驗證的開發原始碼為準。已發布·持續改進

一致性雜湊 文件
一致性雜湊
Consistent hashing conceptsHow it worksImplementationComplexityPractice problemsReal-world use
討論

一致性雜湊 指南 · 5/6

Practice problems

本章目前僅提供英文版。

Every problem below reuses hash64 and HashRing from the implementation chapter (sorted points plus the owner map from position to node). Try each one yourself before reading the solution.

Problem 1. Each node's share of the ring

Given a ring, compute what fraction of the full 2^64 space each node owns. Vary the vnode count over 1, 10, 100 and 1000 and see how far the largest and smallest shares drift from the average.

Approach: each point owns everything after the previous point up to itself. Walk the sorted points and add (p - previous) mod 2^64 to the owner's total. The predecessor of index 0 is the last point, and Python's pts[-1] handles that wrap for free. A ring with a single point gives a difference of 0, so treat it separately.

RING_SIZE = 1 << 64

def ownership(ring: HashRing) -> dict[str, float]:
    pts = ring.points
    if len(pts) == 1:
        return {ring.owner[pts[0]]: 1.0}
    share: dict[str, int] = {}
    for i, p in enumerate(pts):
        arc = (p - pts[i - 1]) % RING_SIZE   # i == 0 wraps to the last point
        node = ring.owner[p]
        share[node] = share.get(node, 0) + arc
    return {node: s / RING_SIZE for node, s in share.items()}

for v in (1, 10, 100, 1000):
    r = HashRing(vnodes=v)
    for n in range(10):
        r.add(f"node-{n}")
    s = ownership(r)
    print(v, round(max(s.values()) * 10, 2), round(min(s.values()) * 10, 2))

Multiplying by the node count normalizes the average to 1. As vnodes increase, both extremes approach 1.

Problem 2. Replicas in distinct zones

Each node belongs to an availability zone. Pick R replicas for a key that are distinct physical nodes in distinct zones. If not enough qualify, return as many as you found.

Approach: walk clockwise from the key one point at a time, skipping nodes already chosen and zones already used. Stop after one full lap.

import bisect

def zone_replicas(ring: HashRing, zone_of: dict[str, str], key: str, n: int) -> list[str]:
    pts = ring.points
    start = bisect.bisect_left(pts, hash64(key))
    chosen: list[str] = []
    zones: set[str] = set()
    for step in range(len(pts)):
        node = ring.owner[pts[(start + step) % len(pts)]]
        if node in chosen or zone_of[node] in zones:
            continue
        chosen.append(node)
        zones.add(zone_of[node])
        if len(chosen) == n:
            break
    return chosen

zone_of = {"a1": "az-1", "a2": "az-1", "b1": "az-2", "b2": "az-2", "c1": "az-3"}
ring = HashRing(vnodes=50)
for node in zone_of:
    ring.add(node)
print(zone_replicas(ring, zone_of, "order:1001", 3))  # one node from each zone

Problem 3. A migration plan for a new node

Before adding a node, list which hash ranges it takes over and from which existing node. Return tuples where each range excludes start and includes end.

對本章有疑問嗎?
上一章Complexity下一章Real-world use
(start, end, previous_owner)

Approach: in the ring after the addition, each point p of the new node takes over the range from its predecessor up to p. The previous owner is whoever owned p in the ring before the addition. The rule still holds when several new points sit next to each other.

def migration_plan(ring: HashRing, new_node: str) -> list[tuple[int, int, str]]:
    old_points = list(ring.points)
    old_owner = dict(ring.owner)
    ring.add(new_node)
    pts = ring.points
    plan = []
    for i, p in enumerate(pts):
        if ring.owner[p] != new_node:
            continue
        j = bisect.bisect_left(old_points, p) % len(old_points)
        plan.append((pts[i - 1], p, old_owner[old_points[j]]))
    return plan

def in_range(h: int, start: int, end: int) -> bool:
    if start < end:
        return start < h <= end
    return h > start or h <= end   # the range wraps past 0

To verify, look up a few thousand keys before and after the change and check that every key that changed owner falls inside a planned range with the matching previous owner, and that no other key moved.

Problem 4. Weighted rendezvous hashing

Nodes have capacity weights. Build a rendezvous hash that assigns keys in proportion to weight and moves only the removed node's keys when one node leaves.

Approach: for each node, turn a hash of node and key into a uniform number u between 0 and 1, and pick the node with the largest score -w / ln(u). That score wins with probability proportional to w. Using the top 53 bits plus 0.5 keeps u strictly between 0 and 1.

import math
from collections import Counter

def hrw(key: str, weights: dict[str, float]) -> str:
    best, best_score = "", -math.inf
    for node, w in weights.items():
        u = ((hash64(f"{node}:{key}") >> 11) + 0.5) / (1 << 53)   # 0 < u < 1
        score = -w / math.log(u)
        if score > best_score:
            best, best_score = node, score
    return best

weights = {"small": 1.0, "medium": 2.0, "large": 4.0}
keys = [f"obj:{i}" for i in range(70_000)]
first = {k: hrw(k, weights) for k in keys}
print(Counter(first.values()))   # roughly 10000 / 20000 / 40000
del weights["medium"]
moved = [k for k in keys if hrw(k, weights) != first[k]]
print(all(first[k] == "medium" for k in moved))  # True

Summary

  • A node's share is the sum of the gaps in front of its points.
  • Replica selection walks clockwise and skips points that break the rules.
  • A migration plan pairs each new point's preceding range with its old owner.
  • The -w / ln(u) score gives weighted rendezvous hashing with minimal movement.

0 則留言

熱門留言由新到舊

登入 · 登入後即可留言。