lolly/docs/config/load-balancing/consistent-hash.conf
xfy 6543422281 docs: 添加 Nginx 配置和 Lua 脚本示例文档
- config: 反向代理、缓存、负载均衡、安全、SSL 等配置模板
- lua: API 网关、认证、动态路由、限流、WebSocket 等脚本示例

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 17:59:22 +08:00

110 lines
3.0 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ============================================================
# Nginx 负载均衡 - 一致性哈希配置示例
# ============================================================
#
# 功能说明:
# - 基于请求特征哈希分配服务器
# - 服务器变更时最小化影响范围
# - 支持虚拟节点实现更均匀分布
#
# Lolly 对应配置:
# server:
# proxy:
# - path: "/api"
# targets:
# - url: "http://backend1:8080"
# - url: "http://backend2:8080"
# - url: "http://backend3:8080"
# load_balance: "consistent_hash"
# hash_key: "ip" # 可选值: ip, uri, "header:X-Custom"
# virtual_nodes: 150 # 默认值
# ============================================================
# 基于 URI 的哈希(缓存场景)
upstream cache_backend {
# 一致性哈希
# Lolly 对应: load_balance: "consistent_hash"
hash $request_uri consistent;
server backend1:8080;
server backend2:8080;
server3:8080;
}
# 基于 IP 的哈希(会话保持)
upstream session_backend {
hash $remote_addr consistent;
server backend1:8080;
server backend2:8080;
server backend3:8080;
}
# 基于 Header 的哈希
upstream user_backend {
# 根据用户 ID Header 分配
# Lolly 对应: hash_key: "header:X-User-ID"
hash $http_x_user_id consistent;
server backend1:8080;
server backend2:8080;
server backend3:8080;
}
server {
listen 80;
server_name consistent.example.com;
# 缓存场景 - 基于 URI
location /cache {
proxy_pass http://cache_backend;
proxy_set_header Host $host;
}
# 会话场景 - 基于 IP
location /session {
proxy_pass http://session_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 用户场景 - 基于 Header
location /user {
proxy_pass http://user_backend;
proxy_set_header Host $host;
proxy_set_header X-User-ID $http_x_user_id;
}
}
# 一致性哈希算法说明:
#
# 1. 工作原理:
# - 将服务器映射到哈希环上0 ~ 2^32-1
# - 请求特征哈希后查找最近的服务器
# - 虚拟节点使分布更均匀
#
# 2. 虚拟节点:
# - 每个服务器对应多个虚拟节点
# - Lolly 默认 150 个虚拟节点
# - 解决服务器数量少时分布不均匀问题
#
# 3. 优势 vs IP 哈希:
# - 服务器增减仅影响部分请求(约 1/N
# - 支持动态伸缩
# - 可选择哈希键IP、URI、Header
#
# 4. 适用场景:
# - 缓存服务(相同 URI 路由到相同服务器)
# - 会话保持(相同用户到相同服务器)
# - 分片存储(数据按特征分布)
#
# 5. 哈希键选择:
# - $remote_addr: 客户端 IP会话保持
# - $request_uri: 请求 URI缓存
# - $http_header_name: 自定义 Header用户分片
#
# 6. Lolly 配置对照:
# hash_key 参数:
# - "ip" -> hash $remote_addr
# - "uri" -> hash $request_uri
# - "header:X-User-ID" -> hash $http_x_user_id