Nginx在局域網(wǎng)內(nèi)實(shí)現(xiàn)真正的ip_hash負(fù)載均衡
遇到的問題
本人在以前公司的局域網(wǎng)內(nèi)搭載Nginx負(fù)載均衡的時候發(fā)現(xiàn)使用ip_hash實(shí)現(xiàn)負(fù)載均衡會發(fā)生一個奇怪的顯現(xiàn),所有客戶端的請求訪問都打在了同一個服務(wù)器上!
這使得負(fù)載均衡根本就沒有起到任何作用,本人查閱了相關(guān)資料最終發(fā)現(xiàn)解決方法,多謝網(wǎng)上的各位大神,參考文獻(xiàn)在最后說明。
為什么無法實(shí)現(xiàn)在同一局域網(wǎng)內(nèi)ip_hash負(fù)載均衡說明
在同一個局域網(wǎng)中,大多數(shù)情況下我們在同一局域網(wǎng)內(nèi)的所有機(jī)器IP前3位都是相同的,假設(shè)都為192.168.1.xxx。
根據(jù)官方的解析(參考網(wǎng)上大神的說法)
This directive causes requests to be distributed between upstreams based on the IP-address of the client.
The key for the hash is the class-C network address or the entire IPv6-address of the client. IPv6 is supported for ip_hash since 1.3.2 or 1.2.2. This method guarantees that the client request will always be transferred to the same server. But if this server is considered inoperative, then the request of this client will be transferred to another server. This gives a high probability clients will always connect to the same server. (簡譯:將客戶端ip轉(zhuǎn)化成C類網(wǎng)絡(luò)地址,然后將該網(wǎng)絡(luò)地址當(dāng)作hash關(guān)鍵字,來保證這個客戶端請求總是被轉(zhuǎn)發(fā)到一臺服務(wù)器上)
由此可以知道ip_hash是用C類IP地址的前3位網(wǎng)絡(luò)號碼進(jìn)行hash計(jì)算的。
(C類IP地址是指在IP地址的四段號碼中,前三段號碼為網(wǎng)絡(luò)號碼,剩下的一段號碼為本地計(jì)算機(jī)的號碼,解析來自百度百科)
到此問題就很明顯了,由于我們在同一局域網(wǎng)內(nèi),ip地址的前3位都是一樣的,不管你是那臺客服端發(fā)送的請求,hash計(jì)算出來的值都是一樣的,所以所有的請問訪問都會打在同一個服務(wù)器上,導(dǎo)致沒有實(shí)現(xiàn)真正的負(fù)載均衡!
修改ip_hash代碼算法中的取值,解決問題
1.在我們下載好的Nginx按轉(zhuǎn)包中打開壓縮包(以1.18.0版本為例子)

2.找到nginx目錄下的src/http/modules/ngx_http_upstream_ip_hash_module.c文件

3.打開該文件,在180行左右會找到hash變量的賦值語句

4.修改iphp->addrlen長度(一共有3處地方需要修改)

5.保存修改
在保存中xx.tar.gz文件不允許修改后直接保存,360壓縮可以直接轉(zhuǎn)為zip保存,這個沒啥影響,如果不想轉(zhuǎn)為zip,可先解壓把ngx_http_upstream_ip_hash_module.c文件修改好后直接替換。
6.把重新編寫過的Nginx安裝在服務(wù)器上,這時候ip_hash在局域網(wǎng)內(nèi)客戶端發(fā)送請求就能實(shí)現(xiàn)真正的負(fù)載均衡,會發(fā)送到不同的服務(wù)器上。