upstream 支持4種負(fù)載均衡調(diào)度算法:
A)輪詢(默認(rèn)):每個(gè)請(qǐng)求按時(shí)間順序逐一分配到不同的后端服務(wù)器;
B)ip_hash:每個(gè)請(qǐng)求按訪問IP的hash結(jié)果分配,同一個(gè)IP客戶端固定訪問一個(gè)后端服務(wù)器;
C)url_hash:按訪問url的hash結(jié)果來(lái)分配請(qǐng)求,使每個(gè)url定向到同一個(gè)后端服務(wù)器;
D)fair:這是比上面兩個(gè)更加智能的負(fù)載均衡算法。此種算法可以依據(jù)頁(yè)面大小和加載時(shí)間長(zhǎng)短智能地進(jìn) 行負(fù)載均衡,也就是根據(jù)后端服務(wù)器的響應(yīng)時(shí)間來(lái)分配請(qǐng)求,響應(yīng)時(shí)間短的優(yōu)先分配。Nginx本身是不支持 fair的,如果需要使用這種調(diào)度算法,必須下載Nginx的upstream_fair模塊。
1)默認(rèn)輪訓(xùn)
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
...
upstream roundrobin { //定義調(diào)度算法
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; //返回真實(shí)IP
proxy_pass http://roundrobin; //代理指向調(diào)度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
然后訪問驗(yàn)證~
客戶端能正常輪流訪問兩個(gè)WEB服務(wù)器; 查看兩個(gè)WEB服務(wù)器的日志。
2)基于hash
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
...
upstream roundrobin {
ip_hash; //添加參數(shù)支持哈希
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
然后訪問驗(yàn)證~
只能訪問一個(gè)WEB服務(wù)器; 查看兩個(gè)WEB服務(wù)器的日志。
3)設(shè)置后端負(fù)載均衡服務(wù)器的狀態(tài):
down,表示當(dāng)前的server暫時(shí)不參與負(fù)載均衡。 backup,預(yù)留的備份機(jī)器。當(dāng)其他所有的非backup機(jī)器出現(xiàn)故障或者忙的時(shí)候,才會(huì)請(qǐng)求backup機(jī)器,因 此這臺(tái)機(jī)器的壓力最輕。
注意:backup不能和ip_hash同時(shí)配置。因?yàn)閕p_hash只能訪問同一臺(tái)服務(wù)器,而backup是在只有所有參與
負(fù)載均衡的服務(wù)器出現(xiàn)故障時(shí),才會(huì)請(qǐng)求備份機(jī)。當(dāng)所有負(fù)載均衡的服務(wù)器出現(xiàn)故障了,ip_hash的將無(wú)法 請(qǐng)求了。
[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; //設(shè)置備份機(jī)器
}
[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
關(guān)閉兩臺(tái)WEB服務(wù)器,能訪問到備機(jī); 注意:只有所有參與負(fù)載均衡的服務(wù)器出現(xiàn)故障時(shí),才會(huì)請(qǐng)求備份機(jī)
總結(jié)
以上所述是小編給大家介紹的nginx四種調(diào)度算法和進(jìn)階,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!