当前位置:   首页安装配置主机算法:深入浅析nginx四种调度算法和进阶

主机算法:深入浅析nginx四种调度算法和进阶

发布日期:2021-12-03 09:21 | 文章来源:站长之家

upstream 支持4种负载均衡调度算法:

A)轮询(默认):每个请求按时间顺序逐一分配到不同的后端主机;

B)ip_hash:每个请求按访问IP的hash结果分配,同一个IP客户端固定访问一个后端主机;

C)url_hash:按访问url的hash结果来分配请求,使每个url定向到同一个后端主机;

D)fair:这是比上面两个更加智能的负载均衡算法。此种算法可以依据页面大小和加载时间长短智能地进 行负载均衡,也就是根据后端主机的响应时间来分配请求,响应时间短的优先分配。Nginx本身是不支持 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四种调度算法和进阶,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对本站网站的支持!

联系我们
关于使用场景和技术架构的更多咨询,请联系我们的销售和技术支持团队。
Yingsoo Host

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部