tomcat 二級域名 session共享

轉自:http://blog.csdn.net/it_man/article/details/38367123

最新項目中服務器出現了點問題,找人幫忙分析了下,順便看了下主從數據庫的讀庫,發現CPU、內存的壓力遠比寫庫的高以

因爲做了memchached緩存,覺得壓力不會太高,而且緩存服務器的CPU、內存使用率並不高,覺得會不會是memchached的session共享出的問題,

做了下實驗,在登錄其中一臺機器登陸後,直接更換IP切換到另外一臺服務器上系統自動退出,session不一致,但是問題來了,系統在運行的時候如果session不共享的話登錄系統肯定會出現經常推出的問題,我直接通過負載的域名訪問不同機器發現session是一致的,然後從網上找啊找最終發現不同的域名會出現這個問題,那不同的IP肯定一樣會出現這種情況,具體原因跟解決方案直接引用。

Tomcat下,不同的二級域名之間或根域與子域之間,Session默認是不共享的,因爲Cookie名稱爲JSESSIONID的Cookie根域是默認是沒設置 的,訪問不同的二級域名,其Cookie就重新生成,而session就是根據這個Cookie來生成的,所以在不同的二級域名下生成的Session也 不一樣。找到了其原因,就可根據這個原因對Tomcat在生成Session時進行相應的修改(注:本文針對Tomcat 6.0.18)。

方案一:

修改tomcat源代碼 包:catalina.jar 
類:org.apache.catalina.connector.Request

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. protected void configureSessionCookie(Cookie cookie) {         
[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1.   cookie.setMaxAge(-1);   
  2.         String contextPath = null;   
  3.         if (!connector.getEmptySessionPath() && (getContext() != null)) {   
  4.             contextPath = getContext().getEncodedPath();         
[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1.   }   
  2.         if ((contextPath != null) && (contextPath.length() > 0)) {         
[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1.       cookie.setPath(contextPath);          
[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1.  } else {   
  2.             cookie.setPath("/");         }   
  3.         String value = System.getProperty("webDomain");       
[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1.     if ((null !=value) && (value.length()>0) && (value.indexOf(".") != -1)) {   
[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1.             cookie.setDomain((value.startsWith("."))?value:"."+value);       
[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1.     }   
  2.         if (isSecure()) {   
  3.             cookie.setSecure(true);         }     
[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1.   }  


重新編譯Tomcat:編譯tomcat  
修改配置:tomcat\conf\catalina.properties,在最後添加一行 webDomain=***.com

 

方案二:

網上其他方案

Usage: 
 - compile CrossSubdomainSessionValve & put it in a .jar file 
 - put that .jar file in $CATALINA_HOME/lib directory 
 - include a <Valve className="org.three3s.valves.CrossSubdomainSessionValve"/> in 
$CATALINA_HOME/conf/server.xml

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package org.three3s.valves;  
  2.   
  3. import java.io.*;  
  4.   
  5. import javax.servlet.*;  
  6. import javax.servlet.http.*;  
  7.   
  8. import org.apache.catalina.*;  
  9. import org.apache.catalina.connector.*;  
  10. import org.apache.catalina.valves.*;  
  11. import org.apache.tomcat.util.buf.*;  
  12. import org.apache.tomcat.util.http.*;  
  13.   
  14. /** <p>Replaces the domain of the session cookie generated by Tomcat 
  15. with a domain that allows that 
  16.  * session cookie to be shared across subdomains.  This valve digs 
  17. down into the response headers 
  18.  * and replaces the Set-Cookie header for the session cookie, instead 
  19. of futilely trying to 
  20.  * modify an existing Cookie object like the example at 
  21. http://www.esus.be/blog/?p=3.  That 
  22.  * approach does not work (at least as of Tomcat 6.0.14) because the 
  23.  * <code>org.apache.catalina.connector.Response.addCookieInternal</code> 
  24. method renders the 
  25.  * cookie into the Set-Cookie response header immediately, making any 
  26. subsequent modifying calls 
  27.  * on the Cookie object ultimately pointless.</p> 
  28.  * 
  29.  * <p>This results in a single, cross-subdomain session cookie on the 
  30. client that allows the 
  31.  * session to be shared across all subdomains.  However, see the 
  32. {@link getCookieDomain(Request)} 
  33.  * method for limits on the subdomains.</p> 
  34.  * 
  35.  * <p>Note though, that this approach will fail if the response has 
  36. already been committed.  Thus, 
  37.  * this valve forces Tomcat to generate the session cookie and then 
  38. replaces it before invoking 
  39.  * the next valve in the chain.  Hopefully this is early enough in the 
  40. valve-processing chain 
  41.  * that the response will not have already been committed.  You are 
  42. advised to define this 
  43.  * valve as early as possible in server.xml to ensure that the 
  44. response has not already been 
  45.  * committed when this valve is invoked.</p> 
  46.  * 
  47.  * <p>We recommend that you define this valve in server.xml 
  48. immediately after the Catalina Engine 
  49.  * as follows: 
  50.  * <pre> 
  51.  * <Engine name="Catalina"...> 
  52.  *     <Valve className="org.three3s.valves.CrossSubdomainSessionValve"/> 
  53.  * </pre> 
  54.  * </p> 
  55.  */  
  56. public class CrossSubdomainSessionValve extends ValveBase  
  57. {  
  58.     public CrossSubdomainSessionValve()  
  59.     {  
  60.         super();  
  61.         info = "org.three3s.valves.CrossSubdomainSessionValve/1.0";  
  62.     }  
  63.   
  64.     @Override  
  65.     public void invoke(Request request, Response response) throws  
  66. IOException, ServletException  
  67.     {  
  68.         //this will cause Request.doGetSession to create the session  
  69. cookie if necessary  
  70.         request.getSession(true);  
  71.   
  72.         //replace any Tomcat-generated session cookies with our own  
  73.         Cookie[] cookies = response.getCookies();  
  74.         if (cookies != null)  
  75.         {  
  76.             for (int i = 0; i < cookies.length; i++)  
  77.             {  
  78.                 Cookie cookie = cookies[i];  
  79.                 containerLog.debug("CrossSubdomainSessionValve: Cookie  
  80. name is " + cookie.getName());  
  81.                 if (Globals.SESSION_COOKIE_NAME.equals(cookie.getName()))  
  82.                     replaceCookie(request, response, cookie);  
  83.             }  
  84.         }  
  85.   
  86.         //process the next valve  
  87.         getNext().invoke(request, response);  
  88.     }  
  89.   
  90.     /** Replaces the value of the response header used to set the 
  91. specified cookie to a value 
  92.      * with the cookie's domain set to the value returned by 
  93. <code>getCookieDomain(request)</code> 
  94.      * 
  95.      * @param request 
  96.      * @param response 
  97.      * @param cookie cookie to be replaced. 
  98.      */  
  99.     @SuppressWarnings("unchecked")  
  100.     protected void replaceCookie(Request request, Response response,  
  101. Cookie cookie)  
  102.     {  
  103.         //copy the existing session cookie, but use a different domain  
  104.         Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue());  
  105.         if (cookie.getPath() != null)  
  106.             newCookie.setPath(cookie.getPath());  
  107.         newCookie.setDomain(getCookieDomain(request));  
  108.         newCookie.setMaxAge(cookie.getMaxAge());  
  109.         newCookie.setVersion(cookie.getVersion());  
  110.         if (cookie.getComment() != null)  
  111.             newCookie.setComment(cookie.getComment());  
  112.         newCookie.setSecure(cookie.getSecure());  
  113.   
  114.         //if the response has already been committed, our replacement  
  115. strategy will have no effect  
  116.         if (response.isCommitted())  
  117.             containerLog.error("CrossSubdomainSessionValve: response  
  118. was already committed!");  
  119.   
  120.         //find the Set-Cookie header for the existing cookie and  
  121. replace its value with new cookie  
  122.         MimeHeaders headers = response.getCoyoteResponse().getMimeHeaders();  
  123.         for (int i = 0, size = headers.size(); i < size; i++)  
  124.         {  
  125.             if (headers.getName(i).equals("Set-Cookie"))  
  126.             {  
  127.                 MessageBytes value = headers.getValue(i);  
  128.                 if (value.indexOf(cookie.getName()) >= 0)  
  129.                 {  
  130.                     StringBuffer buffer = new StringBuffer();  
  131.                     ServerCookie.appendCookieValue(buffer,  
  132. newCookie.getVersion(), newCookie  
  133.                             .getName(), newCookie.getValue(),  
  134. newCookie.getPath(), newCookie  
  135.                             .getDomain(), newCookie.getComment(),  
  136. newCookie.getMaxAge(), newCookie  
  137.                             .getSecure());  
  138.                     containerLog.debug("CrossSubdomainSessionValve:  
  139. old Set-Cookie value: "  
  140.                             + value.toString());  
  141.                     containerLog.debug("CrossSubdomainSessionValve:  
  142. new Set-Cookie value: " + buffer);  
  143.                     value.setString(buffer.toString());  
  144.                 }  
  145.             }  
  146.         }  
  147.     }  
  148.   
  149.     /** Returns the last two parts of the specified request's server 
  150. name preceded by a dot. 
  151.      * Using this as the session cookie's domain allows the session to 
  152. be shared across subdomains. 
  153.      * Note that this implies the session can only be used with 
  154. domains consisting of two or 
  155.      * three parts, according to the domain-matching rules specified 
  156. in RFC 2109 and RFC 2965. 
  157.      * 
  158.      * <p>Examples:</p> 
  159.      * <ul> 
  160.      * <li>foo.com => .foo.com</li> 
  161.      * <li>www.foo.com => .foo.com</li> 
  162.      * <li>bar.foo.com => .foo.com</li> 
  163.      * <li>abc.bar.foo.com => .foo.com - this means cookie won't work 
  164. on abc.bar.foo.com!</li> 
  165.      * </ul> 
  166.      * 
  167.      * @param request provides the server name used to create cookie domain. 
  168.      * @return the last two parts of the specified request's server 
  169. name preceded by a dot. 
  170.      */  
  171.     protected String getCookieDomain(Request request)  
  172.     {  
  173.         String cookieDomain = request.getServerName();  
  174.         String[] parts = cookieDomain.split("\\.");  
  175.         if (parts.length >= 2)  
  176.             cookieDomain = parts[parts.length - 2] + "." +  
  177. parts[parts.length - 1];  
  178.         return "." + cookieDomain;  
  179.     }  
  180.   
  181.     public String toString()  
  182.     {  
  183.         return ("CrossSubdomainSessionValve[container=" +  
  184. container.getName() + ']');  
  185.     }  
  186. }  


放入<Host>標籤中,也可以放到<Engine>標籤中。個人猜想:如果放入<Host>標籤中應該只是當前項目的主域名和二級域名session共享,如果放到<Engine>標籤中,應該是該tomcat下所有的項目都是主域名和二級域名共享(沒有實驗)。

 

方便對於tomcat的二級域名的使用..而導致session失效的解決方法..

需要引用的包是..

下載CrossSubdomainSessionValve包.. 把下載的包,放到$CATALINA_HOME/server/lib 裏面

然後修改tomcat的配置文件: $CATALINA_HOME/conf/server.xml

在標籤"Engine",中添加依家配置標籤..

<Valve className="org.three3s.valves.CrossSubdomainSessionValve"/>  

類似於:

<Engine name="Catalina"...>    
       <valve className="org.three3s.valves.CrossSubdomainSessionValve"/>   

</Engine>

 

 

測試發現,,cookie可以共享,另外發現SESSIONID可以共享。但session中的其他內容不能共享。

 

  • 這是簡單方案。 多臺服務器的話,還需要配置tomcat的session複製。

 

 方案三:

  • 還有一種巧妙的單機方式

最近在做一個jsp的網站遇到了session共享的問題,下面以一個簡單的實例講解一下其中的細節及解決方法:

網站有兩個域名:主域名www.test.com  二級域名xxx.test.com

1、用主域名打開網站,比如訪問www.test.com/login.jsp,這時會產生一個session,並將JSESSIONID=XXXXXXXXXX保存到客戶端Cookie中;

2、接着進行登陸操作,提交表單到www.test.com/checklogin.jsp,  這兩次操作是在同一會話(session)下(假設沒關瀏覽器),why?

     因爲我們再通過主域訪問站點的其他頁面時,第一步在客戶端生成的JSESSIONID(通過cookie方式,如果cookie被禁了則通過url)會提交到服務端

     用於獲取對應的session對象,兩次JSESSIONID一樣,所以兩次的會話保持一致

3、登陸成功後去到了www.test.com/index.jsp 頁面,頁面打印當前的JSESSIONID=XXXXXXXXXX

4、接着通過二級域名訪問index.jsp,即xxx.test.com/index.jsp,這時頁面打印的JSESSIONID=YYYYYYYYYY,也就是說再通過二級域名訪問index.jsp

    這個頁面時session已經改變了,即剛纔的登陸對二級域名下的訪問無效了,why?因爲通過該二級域名訪問index.jsp時,由於無法獲取到主域名生成的JSESSIONID

    所以會重新生成一個session,並把JSESSIONID=YYYYYYYYYY保存到客戶端。

 

如何解決?

我的解決方法:做一個跳轉頁面skip.jsp

<%@ page language="Java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%

 String JSESSIONID = request.getSession().getId();//獲取當前JSESSIONID (不管是從主域還是二級域訪問產生)

 Cookie cookie = new Cookie("JSESSIONID", JSESSIONID);
 cookie.setDomain(".test.com"); //關鍵在這裏,將cookie設成主域名訪問,確保不同域之間都能獲取到該cookie的值,從而確保session統一
 response.addCookie(cookie);  //將cookie返回到客戶端

 request.getRequestDispatcher("indes.jsp").forward(request, response);

%>

 

 方案四:


  • 大型項目出於性能考慮,一般採用session分佈式方案,如: 修改session實現+分佈式緩存memcached

Memcache存儲session,修改tomcat源碼,實現全站二級域名session共享http://blog.csdn.net/jimmy1980/article/details/4975476
使用memcache實現session共享 http://blog.csdn.net/jimmy1980/article/details/4981410

 

 

 

 

 

------------------------------------------other  start--------------------------------------------------

讓tomcat支持2級域名共享session

最近啓用二級域名後,面臨一個主域名與二級域名之間 session 不能共享的問題,帶來的麻煩就是用戶在主域名登陸,但由於二級域名 session 不能共享 ,因此無法進行登陸的操作,對一些功能有一些影響。

問題的原因如下
Tomcat 下,不同的二級域名,Session 默認是不共享的,因爲 Cookie 名稱爲 JSESSIONID 的 Cookie 根域是默認是沒設置的,訪問不同的二級域名,其 Cookie 就重新生成,而 session 就是根據這個 Cookie 來生成的,所以在不同的二級域名下生成的 Session 也不一樣。
找到了其原因,就可根據這個原因對 Tomcat 在生成 Session 時進行相應的修改。

快速解決方案1
在項目的/MET-INF/ 目錄下創建一個 context.xml 文件,內容爲:

1 2
<?xml version="1.0" encoding="UTF-8"?> <Context useHttpOnly="true" sessionCookiePath="/"sessionCookieDomain=".XXXX.com" />

Done!

快速解決方案2:修改 Tomcat 的 server.xml 文件,內容爲:

1
<Context path="" docBase="ROOT" reloadable="false" useHttpOnly="true"sessionCookiePath="/" sessionCookieDomain=".XXXX.com" />

Done!

以上兩種方案的詳細講解見:http://tomcat.apache.org/tomcat-6.0-doc/config/context.html

快速解決方案3
:生成一個叫做 crossSubdomainSessionValve.jar 的文件,用的時候放在 Tomcat lib 目錄下,然後修改 Tomcat server.xml 文件:

1
<Valve className="me.seanchang.CrossSubdomainSessionValve" />



原理:取代由 Tomcat 域產生的會話 cookie ,允許該會話 cookie 跨子域共享。

 

 

測試發現,JSESSIONID不能共享,但cookie可以共享...

後來使用tomcat7版本測試,cookie可以共享,另外發現SESSIONID可以共享。但session中的其他內容不能共享。

------------------------------------------other end--------------------------------------------------------

 方案五:

 經過最後, 通過配置tomcat7,和開發時小改動,成功達到共享session的方案如下:
(不過終極方案還是緩存+session管理接口實現)

 

同一個tomcat多個web應用共享session

tomcat版本:apache-tomcat-6.0.29(次方tomcat6和tomcat7支持)

 

1.修改D:\apache-tomcat-6.0.29\conf\server.xml文件

 


由於每個app都有一個唯一的一個ServletContext 實例對象,下面的所有的servlet 共享此ServletContext。
利用ServletContext 中的setAttribute() 方法把Session 傳遞過去 然後在另外一個app中拿到session實例。


設置爲true 說明你可以調用另外一個WEB應用程序 通過ServletContext.getContext() 獲得ServletContext ;
然後再調用其getattribute() 得到你要的對象。

 

 

 

2.創建兩個web項目

兩個項目訪問URL爲:

        http://localhost:8080/app1/

        http://localhost:8080/app2/

 

app1的index.jsp代碼如下:

app2的index.jsp代碼如下:

3.訪問項目:

 

4.原理(個人淺見)

全局只用app1的session!

app1使用session時,直接使用;其他app使用session的時候通過application獲取app1的session,然後使用。

當瀏覽器關閉,app1的session也就關閉。application的globalSession的value爲null。


獲取application

application爲jsp的九大內置對象,在jsp裏面可以直接使用。在servlet或者struts2的action裏面可以通過request.getSession.getServletContext()獲取!

 

APP1的角色

一般app1扮演“首頁”角色,初始化。後面的項目使用其session。

 

 

 設置crossContext = true,讓兩個應用可以在tomcat中交叉使用上下文環境

 

------------------------------------------------------------

/////////////////////////////////////////////////////////////////////////////////////////

最後,還是得采用基於緩存(Memcache/Redis)的Session共享的方式才能實現,以上實現大都不能解決session裏的數據共享。
redis實現如下:
tomcat-redis-session-manager.jar的下載地址https://github.com/jcoleman/tomcat-redis-session-manager.git。 放到tomcat的lib目錄下(注意此jar依賴的jar也要放到tomcat的lib下)。

 修改tomcat6的server.xml文件如下: 
          
   <Host name="s1.test.com"  appBase="d:/w33"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">
     
   <Context docBase="D:/bak/apache-tomcat-6.0.37/webapps/sso1" path=""  sessionCookiePath="/" sessionCookieDomain=".test.com" sessionCookieName="JSESSIONID" useHttpOnly="true" privileged="true" >
   
   <Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
     
   <Manager className="com.radiadesign.catalina.session.RedisSessionManager"
     host="172.22.203.115"
     port="6379" 
     database="0" 
     maxInactiveInterval="60"/>
   
   </Context>

      </Host>
   
    <Host name="s2.test.com"  appBase="d:/w33"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">

    <Context docBase="D:/bak/apache-tomcat-6.0.37/webapps/sso2" path=""  sessionCookiePath="/" sessionCookieDomain=".test.com" sessionCookieName="JSESSIONID" useHttpOnly="true" privileged="true" >

   <Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
     
   <Manager className="com.radiadesign.catalina.session.RedisSessionManager"
     host="172.22.203.115"
     port="6379" 
     database="0" 
     maxInactiveInterval="60"/>
     
    </Context>
   
    </Host>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章