1. 程式人生 > >terracotta在tomcat叢集中做session共享時session不停變化的問題

terracotta在tomcat叢集中做session共享時session不停變化的問題

Terracotta可以做tomcat叢集的session共享,由於其是jvm級別的cluster解決方案且採用find-gained changes機制,因此在效能要優於memcached,關鍵是其是jvm堆級別的複製,儲存任何值都沒任何問題。

按照官網的說明把所有東西都配置好了,卻發現session無法正常共享。寫了個測試的jsp,打印出session id,單獨訪問某一個tomcat,發現id在不停的換,我一開始懷疑是terracotta沒安好的問題,就又重灌了一遍,問題依舊。這時突然發現在IE下session是正常的,其他瀏覽器下session就不正常,總是不停地換,按說沒有關閉瀏覽器是不會重新生成session的。使用fiddler來檢測請求和響應的header,發現一個奇怪的問題,chrome請求一個頁面時比使用IE時,多了一個對/favicon.ico的請求,而這個請求得到的響應(404)中會產生新的session id使session發生變化。在網站的根目錄下上傳一個favicon.ico即可解決此問題。為了證實是favicon.ico不存在造成的問題,我在頁面中請求了一個不存在的js檔案,結果session id又開始不停地變。把所有不存在的檔案的引用都刪掉能夠解決此問題,但是在沒有使用terracotta前根本不存在此問題,我猜想是不是terraccota在檢測到404錯誤的時候,就會重新生成session的緣故啊。

查了一下tomcat的文件,發現context有個屬性sessionCookiePath,嘗試著把這個值設定為了"/",結果一切正常了,即使再有404錯誤,session也不會再變了。

<Context sessionCookiePath="/"><WatchedResource>WEB-INF/web.xml</WatchedResource></Context>
<!-- <error-page>
		<error-code>404</error-code>
		<location>/Util/404.jsp</location>
</error-page>-->

在web.xml中註釋調改配置即可

官方解釋

The path to be used for all session cookies created for this context. If set, this overrides any path set by the web application. If not set, the value specified by the web application will be used, or the context path used if the web application does not explicitly set one. To configure all web application to use an empty path (this can be useful for portlet specification implementations) set this attribute to / in the global CATALINA_BASE/conf/context.xml file.

不指定此值的時候,是使用的web app中的或者是直接使用context path。我猜測terracotta是接受了此值,但在處理404資源的時候,這個path無法識別,故以為是新的一個會話,造成session改變的緣故。