一、介绍
Nginx upstream可以实现负载均衡。
第三方模块ngx_http_consistent_hash通过一致性哈希算法来选择合适的后端节点。
二、下载、编译到Nginx
2.1 下载
文件名:ngx_http_consistent_hash-master.zip
github下载:https://github.com/replay/ngx_http_consistent_hash
unzip ngx_http_consistent_hash-master.zip
2.2 编译到Nginx
./configure --add-module=/home/guowenyan/ngx_http_consistent_hash-master
make
make install
三、Nginx.conf配置
worker_processes 1;
events {
worker_connections 1024;
}
http {
upstream www.guowenyan.cn {
consistent_hash $request_uri;
server 106.38.193.183:80;
server 106.38.193.182:80;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://www.guowenyan.cn;
}
}
}
四、验证方法
4.1 发送URL请求
多次发送不同的URL请求。
curl -x 127.0.0.1:80 http://www.guowenyan.cn/1.txt -v
4.2 抓包查看upstream到的地址
sudo tcpdump -i any tcp port 80 and host \(106.38.193.183 or 106.38.193.182\) -s0
会发现同一个URL,总是回同一个upstream的IP地址。
参考资料:
Nginx的第三方模块:https://www.nginx.com/resources/wiki/modules/
Nginx的ngx_http_consistent_hash模块的官网使用文档:https://www.nginx.com/resources/wiki/modules/consistent_hash/