nginx学习系列 -- 负载均衡算法 ip_hash 和 hash 和 一致性哈希

1、基于客户端IP地址的hash算法实现的负载均衡:upstream_ip_hash

功能

以客户端的IP地址作为hash算法的关键字,映射到特定的上游服务器中

实现:

对ipv4地址使用前三个字节作为关键字,对ipv6则使用完整的地址

可以基于realip模块修改用于执行算法的IP地址

模块

ngx_http_upstream_ip_hash_module,可以通过 --without-http-upstream_ip_hash_module 禁用该模块

上下文:

upstream 

 

2、基于任意关键字实现Hash算法的负载均衡:upstream_hash模块

功能:

通过指定关键字作为hash_key,基于hash算法映射到指定的上有服务器中

关键字可以含有变量,字符串

模块

ngx_http_upstream_hash_module

通过 --without-http_upstream_hash_module 禁用模块

上下文

hash key [consistent]

upstream

 

 

注意:

当一台上游服务下线了或者损坏了我们不能直接从配置里把server移除,上有服务器数目发生变化,这样会影响以前映射到其他上游服务的也会发生变化,之前的路由策略失效

nginx学习系列 -- 负载均衡算法 ip_hash 和 hash 和 一致性哈希

缓解方案:

用一致性哈希算法

 

一致性哈希算法

nginx学习系列 -- 负载均衡算法 ip_hash 和 hash 和 一致性哈希

使用

在哈希算法key后加consistent  即可