在 Redis 中大量掃描鍵值時,直接使用 KEYS pattern 會阻塞主執行緒,導致服務停頓。本文示範使用 SCAN 迭代器搭配 Pipeline 批次讀取,實現高效能、非阻塞的鍵值遍歷。
import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0)
r = redis.Redis(connection_pool=pool)
pipe = r.pipeline()
pipe_size = 100_000 # 管線批次大小
key_batch = []
for key in r.scan_iter(match='PREFIX_*', count=100_000):
key_batch.append(key)
pipe.get(key)
if len(key_batch) >= pipe_size:
# 批次執行並輸出
for k, v in zip(key_batch, pipe.execute()):
print(k, v)
key_batch.clear()
# 處理剩餘批次
if key_batch:
for k, v in zip(key_batch, pipe.execute()):
print(k, v)
scan_iter 使用游標分批掃描,不阻塞 Redis 主執行緒;count 參數控制每次迴圈掃描數量 (非回傳數量)。GET 打包成單次網路往返,大幅降低 RTT 開銷。原文另附一個使用 os.walk 遍歷資料夾、列印檔案大小並選擇性刪除大檔的腳本:
import os
file_path = input('Enter filepath: ')
for parent, dirnames, filenames in os.walk(file_path):
for fname in filenames:
full = os.path.join(parent, fname)
size_mb = os.path.getsize(full) / 1024 / 1024
print(f'{full} ({size_mb:.3f} MB)')
if size_mb > 50:
if input('Delete? (yes/no): ') == 'yes':
os.remove(full)
KEYS *,務必用 SCAN。pipeline 或 mget/mset。slowlog 找出耗時指令。redis-py-cluster 支援叢集模式。正確使用 SCAN + Pipeline 是 Python 操作 Redis 大量資料的標準模式。