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中,只作了简单的配置,如下:

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页面

[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.html vim /opt/app/code5/6666/5347/index.html vim /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/
固定到一个信息页面上:

猜你喜欢

转载自www.cnblogs.com/ExMan/p/11879174.html