Appearance
负载均衡算法
HAProxy 支持多种负载均衡算法,通过 balance 指令在 backend 中设置。
算法一览
| 算法 | 关键词 | 适用场景 |
|---|---|---|
| Round Robin | roundrobin | 默认,轮流分配,最简单 |
| Weighted Round Robin | roundrobin + server weight | 服务器性能不同时 |
| Least Connections | leastconn | 长连接服务(数据库、API) |
| First Available | first | 优先利用已连接的服务器 |
| Source IP Hash | source | 简单会话保持 |
| URI Hash | uri | 缓存友好型会话保持 |
| URL Parameter Hash | url_param | 按 GET 参数分配 |
| Header Hash | hdr | 按指定 Header 分配 |
| Random | random | 简单随机,最新支持的算法 |
| Random with Load Balancing | random fallback | 随机 + 备用算法 |
1. Round Robin(轮询)
默认算法,按顺序轮流分配给每台服务器:
haproxy
backend web_pool
balance roundrobin
server web1 192.168.1.101:8080 check
server web2 192.168.1.102:8080 check
server web3 192.168.1.103:8080 check2. Weighted Round Robin(加权轮询)
根据服务器性能分配不同权重:
haproxy
backend web_pool
balance roundrobin
server web1 192.168.1.101:8080 check weight 100 # 权重100
server web2 192.168.1.102:8080 check weight 50 # 权重50,分配少一半
server web3 192.168.1.103:8080 check weight 25 # 权重25权重范围 0~256,默认为 1。权重为 0 的服务器不参与负载均衡。
3. Least Connections(最少连接)
分配给当前连接数最少的服务器,适合长连接场景:
haproxy
backend api_pool
balance leastconn
option httpchk GET /health
server api1 192.168.1.201:8000 check
server api2 192.168.1.202:8000 check💡 最佳实践:API 服务、WebSocket、数据库连接池等长连接场景首选 Least Connections。
4. Source IP Hash(源 IP 哈希)
根据客户端 IP 地址计算哈希,同一 IP 永远路由到同一后端:
haproxy
backend web_pool
balance source
server web1 192.168.1.101:8080 check
server web2 192.168.1.102:8080 check带权重的 Source Hash
haproxy
balance source # 默认只哈希 IP
balance source 0 # 0 = 用全部 4 个字节的 IP 计算哈希⚠️ 后端服务器列表变化时会导致大量会话重新分配(rehashing),建议配合
hash-type consistent使用。
5. 一致性哈希(Consistent Hash)
解决服务器变更时的 rehashing 问题:
haproxy
backend web_pool
balance source
hash-type consistent # 启用一致性哈希
server web1 192.168.1.101:8080 check
server web2 192.168.1.102:8080 check新增/移除服务器时,只有少部分会话会重新分配。
6. URI Hash
对请求 URI 做哈希,同一 URI 路由到同一后端。适合缓存服务器场景:
haproxy
backend cache_pool
balance uri len 128 hash mod 211 # 取 URI 前128字符,哈希取模211
server c1 192.168.1.101:6081 check
server c2 192.168.1.102:6081 check常用参数:
len <n>:取 URI 前 n 个字符做哈希depth <n>:取 URI 第几层路径做哈希hash <alg>:哈希算法(default、md5、sha1、map-based、avalanche)mod:取模运算
7. URL 参数 Hash
根据 GET 参数值分配请求:
haproxy
backend user_pool
balance url_param user_id check_post 64
server u1 192.168.1.201:8080 check
server u2 192.168.1.202:8080 check请求 ?user_id=12345 会哈希 12345 来分配。
8. Header Hash
根据指定的 HTTP Header 做哈希:
haproxy
backend web_pool
balance hdr(User-Agent) # 按 User-Agent 哈希
balance hdr(X-Real-IP) # 按自定义 Header 哈希9. Random
纯随机算法,在服务器数量多时分布均匀:
haproxy
backend web_pool
balance random
server web1 192.168.1.101:8080 check
server web2 192.168.1.102:8080 check
server web3 192.168.1.103:8080 checkRandom with Fallback
随机失败后自动切换到备用算法:
haproxy
balance random fallback leastconn算法选择建议
| 场景 | 推荐算法 |
|---|---|
| 普通 Web 网站 | roundrobin |
| API / 长连接 | leastconn |
| 需要会话保持 | source + hash-type consistent |
| CDN / 缓存服务器 | uri |
| 微服务负载均衡 | leastconn 或 source |
| 简单快速选择 | random |