Skip to content

Week12_demo1.py 純 Python 模擬 MapReduce 分散式 Log 統計

這個 demo 的重點在於 “模擬 3 台網頁伺服器(Worker 1, 2, 3)各自產生一疊 HTTP 狀態碼 Log,透過 Map 各自統計、再透過 Reduce 彙整”

from collections import defaultdict
from functools import reduce

# 1. 模擬分散在 3 台不同伺服器硬碟上的 HTTP Log 分塊 (HDFS Blocks)
node1_logs = ['200', '200', '404', '200', '500']
node2_logs = ['200', '404', '404', '200', '200']
node3_logs = ['500', '200', '200', '200', '404']
cluster_blocks = [node1_logs, node2_logs, node3_logs]

# 2. 【Map 階段】每台節點各自在本地計算狀態碼出現次數 (移動運算而非移動資料)
def map_worker(log_chunk):
    local_counts = defaultdict(int)
    for status in log_chunk:
        local_counts[status] += 1
    return dict(local_counts)

mapped_results = list(map(map_worker, cluster_blocks))
print('=== [Map 階段] 3 台伺服器各自回報的局部統計 ===')
for idx, res in enumerate(mapped_results, 1):
    print(f'Worker {idx} 回報: {res}')

# 3. 【Reduce 階段】主節點將各台機器的統計結果彙整加總
def reduce_master(acc, current):
    for status, count in current.items():
        acc[status] = acc.get(status, 0) + count
    return acc

final_summary = reduce(reduce_master, mapped_results, {})
print('\n=== [Reduce 階段] 全叢集最終彙整結果 ===')
print(final_summary)

實際執行輸出畫面

=== [Map 階段] 3 台伺服器各自回報的局部統計 ===
Worker 1 回報: {'200': 3, '404': 1, '500': 1}
Worker 2 回報: {'200': 3, '404': 2}
Worker 3 回報: {'500': 1, '200': 3, '404': 1}

=== [Reduce 階段] 全叢集最終彙整結果 ===
{'200': 9, '404': 4, '500': 2}

輸出畫面觀察重點

# 扣緊 HDFS 與 MapReduce 觀念
# 呼應「HDFS 切塊(Block Splitting)」:
  # 指著 Worker 1 ~ 3 回報 這三行告訴學生:「原本有 15 筆 Log,在真實世界裡
    這代表 1.5 TB 的紀錄,分散存在 3 台不同電腦的硬碟裡。注意看 Worker 2 裡面沒有 
    500 錯誤,這很正常,因為每台機器只看得到自己硬碟裡的那一塊資料。」

# 呼應「移動運算而非移動資料(Data Locality)」:
  #「請同學觀察網路上傳輸了什麼?Worker 1 並沒有把那 5 筆原始 Log 傳給主機,它只是
    傳了一個不到 50 Bytes 的小字典 {'200': 3, '404': 1, '500': 1}!在巨量資料裡,
    這叫做『把小程式送去資料旁邊算,只傳回濃縮結果』,徹底解決網路頻寬塞車的問題。」

# 呼應「Reduce 彙整階段」:
  #「最後主節點(Reduce)的工作非常輕鬆,只要把 3 張小紙條上的 '200' 加起來($3+3+3=9$)、
    '404' 加起來($1+2+1=4$)、'500' 加起來($1+0+1=2$),就得到全叢集的健康度報告!」

Leave a comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *