Varnish 作為前端緩存,後端有多台 Varnish 節點。初期使用輪詢導致後端命中率低,決定改用 URL Hash 根據請求 URL 分發,提升緩存命中。
backend backend1 { .host = "10.0.0.1"; .port = "80"; }
backend backend2 { .host = "10.0.0.2"; .port = "80"; }
director hash_director hash {
{ .backend = backend1; .weight = 1; }
{ .backend = backend2; .weight = 1; }
}
sub vcl_recv {
set req.backend_hint = hash_director;
# 關鍵:保留查詢參數參與 hash,避免參數被過濾導致分發錯誤
set req.hash += req.url + req.http.host;
}vcl_hash 僅用 req.url + req.http.host,若業務依賴 Query String(如 ?id=123),需在 vcl_hash 顯式加入 req.url(已含查詢串)或單獨加入 req.http.X-Custom-Param。weight 僅在 hash 導演中用於虛擬節點數量,非輪詢權重。probe 自動剔除故障節點。使用 varnishlog -g request -q "ReqUrl ~ 'pattern'" 觀察請求分發是否符合預期哈希分布。