精品推薦!Nginx負載均衡—如何自定義URL中的hash key

"例如請求的url為http://www.a.com/{path_var1}/{path_var2}

path_var1和path_var2是兩個path variable

如果現在只想根據path_var1來做路由,即path_var1相同的請求落在同一台伺服器上,應當怎麼配置呢?"

如上的問題,我們都知道nginx的負載均衡,可以支持很多hash方式,對於指定url中的內容進行hash ,接下來我用一個場景來模擬:

1. 場景描述

場景大概就是這樣,當url請求過來時候,通過url中的一個特定數值,進行提取,然後進行hash

2. 配置

1、為了簡單實現場景測試,我在nginx中,只作了簡單的配置,如下:

Advertisements

server { listen 80; server_name defualt www.jesonc.com; location / { proxy_pass http://www_jesonc; index index.html index.htm; }}upstream www_jesonc { server 127.0.0.1:5000; server 127.0.0.1:5001; server 127.0.0.1:5002;}server { listen 5000; server_name defualt www.jesonc.com; location / { root /opt/app/code4; #random_index on; index index.html index.htm; }}server { listen 5001; server_name defualt www.jesonc.com; location / { root /opt/app/code5; index index.html index.htm; }}server { listen 5002; server_name defualt www.jesonc.com; location / { root /opt/app/code6; index index.html index.htm; }}

2、新建目錄,建立index頁面

Advertisements

[root@Jeson-at-imoocc conf.d]# mkdir /opt/app/code4/11231/2131/ -p[root@Jeson-at-imoocc conf.d]# mkdir /opt/app/code4/3123/5345/ -p[root@Jeson-at-imoocc conf.d]# mkdir /opt/app/code4/6666/5347/ -p[root@Jeson-at-imoocc conf.d]# cp /opt/app/code/jesonc.html /opt/app/code4/11231/2131/index.html[root@Jeson-at-imoocc conf.d]# cp /opt/app/code/jesonc.html /opt/app/code4/3123/5345/index.html[root@Jeson-at-imoocc conf.d]# cp /opt/app/code/jesonc.html /opt/app/code4/6666/5347/index.html//編輯index頁面,使內容有區別[root@Jeson-at-imoocc conf.d]# vim /opt/app/code4/3123/5345/index.html[root@Jeson-at-imoocc conf.d]# vim /opt/app/code4/6666/5347/index.html[root@Jeson-at-imoocc conf.d]# vim /opt/app/code4/3123/5345/index.html//拷貝目錄[root@Jeson-at-imoocc app]# cp -r code4 code5[root@Jeson-at-imoocc app]# cp -r code4 code6//編輯index頁面,使內容有區別vim /opt/app/code4/6666/5347/index.htmlvim /opt/app/code5/6666/5347/index.htmlvim /opt/app/code6/6666/5347/index.html

3. 自定義hash key的方式

這樣,我們需要設置的就是,當用戶訪問http://www.jesonc.com/6666/5347/index.html

我們通過哈希url中的6666,固定訪問一個server

設置,改動如下:

 if ( $uri ~* "^\/([^\/]+)\/.*" ){ set $defurlkey $1; }upstream www_jesonc { hash $defurlkey; server 127.0.0.1:5000; server 127.0.0.1:5001; server 127.0.0.1:5002;}

4. 測試

1、在沒有加入hash key之前,訪問http://www.jesonc.com/6666/5347/

頁面將,不斷輪訓展示不同信息。

2、設置完成hash key之後,訪問:http://www.jesonc.com/6666/5347/

固定到一個信息頁面上:

希望大家多多支持,小編致力推薦精品,共享給大家學習交流。歡迎大家隨時留言回復,謝謝大家!

Ps:如果此文為您帶來歡樂,那就關注小編吧。每天精品準時推送!

Advertisements

你可能會喜歡