0.环境:centos7.2,tomcat8.5*2 ,nginx1.0.13
0-1:起因,由于上线不能影响用户使用,起初使用ip分流,但是有些情况无法获取ip,故查到可以用cookie做分流,这样一来,可以给客户以及测试人员分配角色 ,根据角色设置cookie,再根据cookie实现分流,便可实现上线不影响现网使用。
1.nginx配置
upstream nttest{
# server 127.0.0.1:38080;
server 127.0.0.1:39090;
}
upstream nttest1{
server 127.0.0.1:38080;
}
location ^~ /web/ {
set $group nttest;
if ($http_cookie ~* "hyb_test") {
set $group nttest1;
}
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
index index.html index.htm;
proxy_pass http://$group;
}
即,声明2个upstream,分别指向tomcat1和2,当路径匹配到web,设置变量group为nttest节点,判断cookie,如果cookie带有hyb_test,则设置变量group为nttest1节点,将请求代理到group。
2测试用例准备

@RequestMapping("/login")
public String login2(String username,String password, HttpServletRequest req, HttpServletResponse resp){
if("hyb".equals(username)){
Cookie cookie = new Cookie("hyb_test_username",username);
cookie.setPath("/");
// cookie.setDomain("domain");
resp.addCookie(cookie);
}
return "success";
}

将项目拉到2个tomcat,修改2.jsp内容即可,比如我将nttest1下的2.jsp修改为

3测试分流
分别启动tomcat1,tomcat2,正常启动后访问index.jsp

因为没做登陆校验,直接点登陆即可,另开一个窗口,用hyb做用户名登陆,如图

分别点击登陆,

hyb已经成功访问到nttest1,而其他登陆则访问了nttest,分流成功!


网友评论