基於 URL 一致性哈希分發請求至後端 Tomcat 集群,實現會話親和性,避免 Session 複製開銷。
pcre-8.02+:正則支持nginx-0.7.58+:核心版本(現建議 1.20+)ngx_http_upstream_consistent_hash 或 nginx_upstream_hash 模組(現內建 consistent 參數)
upstream tomcat_cluster {
# 一致性哈希,基於請求 URI 分發
consistent;
server 192.168.1.10:8080 weight=1 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 weight=1 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 weight=1 max_fails=3 fail_timeout=30s;
# 可選:基於 Cookie/參數哈希
# consistent $cookie_jsessionid;
# consistent $arg_sessionid;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass https://tomcat_cluster;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 連接池優化
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
# 編譯時添加模組
./configure --add-module=/path/to/nginx_upstream_hash-0.3.1
upstream your.website.name {
server your.tomcat.server.ip1:8080;
server your.tomcat.server.ip2:8080;
# 核心:基於請求 URI 哈希
hash $request_uri;
}
server {
listen 80;
server_name your.website.name;
location / {
proxy_pass https://your.website.name;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
| 指令 | 內建 consistent | 傳統 hash 模組 |
|---|---|---|
| 語法 | consistent [key] | hash key |
| 算法 | Ketama 一致性哈希 | 模運算哈希 |
| 節點變動影響 | 最小化(僅影響該節點請求) | 大範圍重新分發 |
| 權重支持 | 支持 weight | 不支持 |
| 推薦程度 | ⭐⭐⭐⭐⭐ 生產首選 | ⭐⭐ 僅舊版本兼容 |
# 策略一:基於用戶 ID(登錄後)
map $cookie_uid $hash_key {
default $request_uri;
"~^[0-9]+$" $cookie_uid;
}
upstream backend {
consistent $hash_key;
server 10.0.1.10:8080;
server 10.0.1.11:8080;
}
# 策略二:API 接口按參數哈希
location /api/ {
set $api_hash $arg_user_id$arg_device_id;
if ($api_hash = "") { set $api_hash $request_uri; }
proxy_pass https://api_cluster;
# 需在 upstream 中使用 consistent $api_hash
}
upstream tomcat_cluster {
consistent;
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 max_fails=3 fail_timeout=30s;
# 被動檢查:max_fails/fail_timeout
# 主動檢查需 ngx_http_upstream_check_module 或商業版
# 保持長連接
keepalive 64;
}
# 查看 upstream 狀態(需 stub_status 或 vts 模組)
location /nginx_status {
stub_status on;
allow 127.0.0.1; deny all;
}
# 日誌記錄 upstream 選擇
log_format upstream_log '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'upstream=$upstream_addr upstream_status=$upstream_status '
'upstream_response_time=$upstream_response_time '
'upstream_cache_status=$upstream_cache_status';
access_log /var/log/nginx/access.log upstream_log;
keepalive、連接池減少握手開銷$request_uri 不含 Body → 需 API 接口將關鍵標識放 Query String 或 HeaderNginx 現代版本內建 consistent 參數實現一致性哈希,較傳統 hash 模組在節點變動時表現更優、支持權重。核心在於選擇高熵、業務相關的哈希鍵,配合健康檢查、連接池、監控日誌構建生產級負載均衡層。