Nginx:session與nginx_upstream_jvm_route(轉(zhuǎn))
轉(zhuǎn)自http://hanqunfeng.iteye.com/blog/1920994
1)ip_hash(不推薦使用)
nginx中的ip_hash技術(shù)能夠?qū)⒛硞€(gè)ip的請(qǐng)求定向到同一臺(tái)后端,這樣一來(lái)這個(gè)ip下的某個(gè)客戶端和某個(gè)后端就能建立起穩(wěn)固的session,ip_hash是在upstream配置中定義的:
- upstream backend {
- server 127.0.0.1:8080 ;
- server 127.0.0.1:9090 ;
- ip_hash;
- }
不推薦使用的原因如下:
1/ nginx不是最前端的服務(wù)器。
ip_hash要求nginx一定是最前端的服務(wù)器,否則nginx得不到正確ip,就不能根據(jù)ip作hash。譬如使用的是squid為最前端,那么nginx取ip時(shí)只能得到squid的服務(wù)器ip地址,用這個(gè)地址來(lái)作分流是肯定錯(cuò)亂的。
2/ nginx的后端還有其它方式的負(fù)載均衡。
假如nginx后端又有其它負(fù)載均衡,將請(qǐng)求又通過(guò)另外的方式分流了,那么某個(gè)客戶端的請(qǐng)求肯定不能定位到同一臺(tái)session應(yīng)用服務(wù)器上。
3/ 多個(gè)外網(wǎng)出口。
很多公司上網(wǎng)有多個(gè)出口,多個(gè)ip地址,用戶訪問(wèn)互聯(lián)網(wǎng)時(shí)候自動(dòng)切換ip。而且這種情況不在少數(shù)。使用 ip_hash 的話對(duì)這種情況的用戶無(wú)效,無(wú)法將某個(gè)用戶綁定在固定的tomcat上 。
2)nginx_upstream_jvm_route(nginx擴(kuò)展,推薦使用)
nginx_upstream_jvm_route 是一個(gè)nginx的擴(kuò)展模塊,用來(lái)實(shí)現(xiàn)基于 Cookie 的 Session Sticky 的功能。
簡(jiǎn)單來(lái)說(shuō),它是基于cookie中的JSESSIONID來(lái)決定將請(qǐng)求發(fā)送給后端的哪個(gè)server,nginx_upstream_jvm_route會(huì)在用戶第一次請(qǐng)求后端server時(shí),將響應(yīng)的server標(biāo)識(shí)綁定到cookie中的JSESSIONID中,從而當(dāng)用戶發(fā)起下一次請(qǐng)求時(shí),nginx會(huì)根據(jù)JSESSIONID來(lái)決定由哪個(gè)后端server來(lái)處理。
1/ nginx_upstream_jvm_route安裝
下載地址(svn):http://nginx-upstream-jvm-route.googlecode.com/svn/trunk/
假設(shè)nginx_upstream_jvm_route下載后的路徑為/usr/local/nginx_upstream_jvm_route,
(1)進(jìn)入nginx源碼路徑
patch -p0 < /usr/local/nginx_upstream_jvm_route/jvm_route.patch
(2)./configure --with-http_stub_status_module --with-http_ssl_module --prefix=/usr/local/nginx --with-pcre=/usr/local/pcre-8.33 --add-module=/usr/local/nginx_upstream_jvm_route
(3)make & make install
關(guān)于nginx的下載與安裝參考:http://hanqunfeng.iteye.com/blog/697696
2/ nginx配置
- upstream tomcats_jvm_route
- {
- # ip_hash;
- server 192.168.33.10:8090 srun_id=tomcat01;
- server 192.168.33.11:8090 srun_id=tomcat02;
- jvm_route $cookie_JSESSIONID|sessionid reverse;
- }
3/ tomcat配置
修改192.168.33.10:8090tomcat的server.xml,
- 將
- <Engine name="Catalina" defaultHost="localhost" >
- 修改為:
- <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat01">
同理,在192.168.33.11:8090server.xml中增加jvmRoute="tomcat02"。
4/ 測(cè)試
啟動(dòng)tomcat和nginx,訪問(wèn)nginx代理,使用Google瀏覽器,F(xiàn)12,查看cookie中的JSESSIONID,
形如:ABCD123456OIUH897SDFSDF.tomcat01 ,刷新也不會(huì)變化
posted on 2014-03-28 11:39 小秦 閱讀(531) 評(píng)論(0) 編輯 收藏