nginx實(shí)現(xiàn)根據(jù)cookie分流

0.環(huán)境:centos7.2,tomcat8.5*2 ,nginx1.0.13

0-1:起因,由于上線不能影響用戶使用,起初使用ip分流,但是有些情況無(wú)法獲取ip,故查到可以用cookie做分流,這樣一來(lái),可以給客戶以及測(cè)試人員分配角色 ,根據(jù)角色設(shè)置cookie,再根據(jù)cookie實(shí)現(xiàn)分流,便可實(shí)現(xiàn)上線不影響現(xiàn)網(wǎng)使用。

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個(gè)upstream,分別指向tomcat1和2,當(dāng)路徑匹配到web,設(shè)置變量group為nttest節(jié)點(diǎn),判斷cookie,如果cookie帶有hyb_test,則設(shè)置變量group為nttest1節(jié)點(diǎn),將請(qǐng)求代理到group。

2測(cè)試用例準(zhǔn)備

index.jsp
 @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";
    }
跳轉(zhuǎn)頁(yè)面

將項(xiàng)目拉到2個(gè)tomcat,修改2.jsp內(nèi)容即可,比如我將nttest1下的2.jsp修改為
image.png

3測(cè)試分流

分別啟動(dòng)tomcat1,tomcat2,正常啟動(dòng)后訪問index.jsp


index

因?yàn)闆]做登陸校驗(yàn),直接點(diǎn)登陸即可,另開一個(gè)窗口,用hyb做用戶名登陸,如圖


image.png

分別點(diǎn)擊登陸,
image.png

hyb已經(jīng)成功訪問到nttest1,而其他登陸則訪問了nttest,分流成功!

再看cookie
image.png
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容