Nginx四种负载均衡调度算法概述
Nginx的upstream模块提供了四种负载均衡调度算法供选择:
A) 轮询(默认方式):按照请求到达的时间顺序,依次将每个请求分配给不同的后端服务器处理;
B) ip_hash:根据访问客户端IP地址计算哈希值进行分配,确保来自同一IP的请求始终指向同一个后端服务器;
C) url_hash:依据访问URL的哈希结果来分配请求,保证相同的URL总是被路由到同一个后端服务器;
D) fair:这是一种更为智能的负载均衡算法。它根据后端服务器的响应时间长短动态调整负载,优先将请求分配给响应时间短的服务器。原生Nginx不支持此算法,若需使用必须下载并安装upstream_fair第三方模块。
1)默认轮询模式配置
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
...
upstream roundrobin { //定义调度算法
server 192.168.31.33 weight=1; //server1
server 192.168.31.237 weight=1; //server2
}
...
location / {
proxy_set_header X-Real-IP $remote_addr; //返回真实IP
proxy_pass http://roundrobin; //代理指向调度roundrobin
}
[root@proxy ~]# killall -9 nginx
[root@proxy ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@proxy ~]# nginx
完成配置后访问验证~
客户端能够正常轮流访问两台WEB服务器;通过查看两台WEB服务器的日志可以确认请求分发情况。
2)基于hash模式配置
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
...
upstream roundrobin {
ip_hash; //添加参数支持哈希
server 192.168.31.33 weight=1;
server 192.168.31.237 weight=1;
}
[root@proxy ~]# killall -9 nginx
[root@proxy ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@proxy ~]# nginx
完成配置后访问验证~
此时只能访问到一台WEB服务器;通过查看两台WEB服务器的日志可发现另一台无请求记录。
3)设置后端负载均衡服务器的状态:
down:表示当前server暂时不参与负载均衡。backup:预留的备份机器。当其他所有非backup机器出现故障或繁忙时,才会请求backup机器,因此这台机器的压力最轻。
注意:backup不能和ip_hash同时配置。因为ip_hash只能访问同一台服务器,而backup是在只有所有参与
负载均衡的服务器出现故障时,才会请求备份机。当所有负载均衡的服务器出现故障了,ip_hash的将无法请求了。
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
upstream roundrobin {
server 192.168.31.33 weight=1;
server 192.168.31.35 weight=1;
server 192.168.31.237 backup; //设置备份机器
}
[root@proxy ~]# killall -9 nginx
[root@proxy ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@proxy ~]# nginx
关闭两台WEB服务器,能访问到备机;注意:只有所有参与负载均衡的服务器出现故障时,才会请求备份机
总结
以上所述是小编给大家介绍的nginx四种调度算法和进阶,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对本站网站的支持!