摘要:PersistentManager
與StandardManager
的異同。
之前兩篇關于session的文章主要討論了session相關的創建、查詢、過期處理。而我們查看源碼的時候都是默認實現是StandardManager
類,實際上實現也可以是PersistentManager
類,下面我們就查看下該類的相關方法。
我們都知道PersistentManager
代表的是持久化session的管理器。在PersistentManager
類定義中有個變量org.apache.catalina.Store
,該變量表示session管理器持久化session的方式,具體類圖如下:
Store
持久化存儲方式的抽象類,定義了一些基本方法,例如save()
,load()
,keys()
,clear()
等。save()
用來將session持久化到持久性介質中。load()
方法從持久化介質中讀取到內存中,keys()
則返回所有的sessionId數組。clear()
則清除所有的session。
StoreBase
抽象類,對Store
作了基本實現。
FileStore
該類會將session對象存儲到某個文件中,文件名會使用session對象的標識符再加上一個后綴.session
構成。文件位于臨時目錄下,也可以調用FileStore
類的setDirectroy()
方法修改目錄。
JDBCStore
該類將session對象通過jdbc存入數據庫,因此使用該類需要使用jdbc鏈接。
鑒于save()
,load()
源碼都很簡單這里就不一一查看了。
我們繼續討論PersistentManager
類相關方法。
在Request
的doGetSession()
方法中,我們之前默認manager
實現類是StandardManager
,如果tomcat中配置的是PersistentManager
,那么manager.findSession(requestedSessionId)
會略有不同,我們查看下源碼(在PersistentManagerBase
類中):
@Override
public Session findSession(String id) throws IOException {//調用父類的findSession() 也就是ManagerBase類中的findSession,從現有內存中查找是否有指定的sessionSession session = super.findSession(id);// OK, at this point, we're not sure if another thread is trying to// remove the session or not so the only way around this is to lock it// (or attempt to) and then try to get it by this session id again. If// the other code ran swapOut, then we should get a null back during// this run, and if not, we lock it out so we can access the session// safely.//翻譯下 英文注釋// 代碼運行到這里,因為我們不確定是否有別的線程要移除這個session,所以最保險的辦法就是加鎖再次嘗試獲取該session// 如果有其他代碼正在執行 swapOut(將內存session持久化到介質中),那么我們應該返回null,如果沒有的話,那么我們就可以安全的訪問這個sessionif(session != null) {synchronized(session){session = super.findSession(session.getIdInternal());if(session != null){// To keep any external calling code from messing up the// concurrency.session.access();session.endAccess();}}}// 再次判斷if (session != null)return session;// See if the Session is in the Store//從持久化介質中查找 session是否存在session = swapIn(id);return session;
}
查看 swapIn()
方法:
/*** Look for a session in the Store and, if found, restore* it in the Manager's list of active sessions if appropriate.* The session will be removed from the Store after swapping* in, but will not be added to the active session list if it* is invalid or past its expiration.** @return restored session, or {@code null}, if none is found*//*** 在Store(存儲介質)中查找session,如果發現將把session恢復到該Manager的活躍session集合中。* 這個session將會從Store中移除,但是如果session過期或者無效將不會添加到活躍集合。*/protected Session swapIn(String id) throws IOException {if (store == null)return null;Object swapInLock = null;/** The purpose of this sync and these locks is to make sure that a* session is only loaded once. It doesn't matter if the lock is removed* and then another thread enters this method and tries to load the same* session. That thread will re-create a swapIn lock for that session,* quickly find that the session is already in sessions, use it and* carry on.*/synchronized (this) {swapInLock = sessionSwapInLocks.get(id);if (swapInLock == null) {swapInLock = new Object();sessionSwapInLocks.put(id, swapInLock);}}Session session = null;synchronized (swapInLock) {// First check to see if another thread has loaded the session into// the managersession = sessions.get(id);if (session == null) {try {if (SecurityUtil.isPackageProtectionEnabled()){try {session = AccessController.doPrivileged(new PrivilegedStoreLoad(id));} catch (PrivilegedActionException ex) {Exception e = ex.getException();log.error(sm.getString("persistentManager.swapInException", id),e);if (e instanceof IOException){throw (IOException)e;} else if (e instanceof ClassNotFoundException) {throw (ClassNotFoundException)e;}}} else {//加載session//1111111session = store.load(id);}} catch (ClassNotFoundException e) {String msg = sm.getString("persistentManager.deserializeError", id);log.error(msg, e);throw new IllegalStateException(msg, e);}if (session != null && !session.isValid()) {log.error(sm.getString("persistentManager.swapInInvalid", id));session.expire();removeSession(id);session = null;}if (session != null) {if(log.isDebugEnabled())log.debug(sm.getString("persistentManager.swapIn", id));session.setManager(this);// make sure the listeners know about it.((StandardSession)session).tellNew();add(session);((StandardSession)session).activate();// endAccess() to ensure timeouts happen correctly.// access() to keep access count correct or it will end up// negativesession.access();session.endAccess();}}}// Make sure the lock is removedsynchronized (this) {sessionSwapInLocks.remove(id);}return session;
}
可以看到主要的核心代碼就是標注1的地方,Store.load(id)
,而這個源碼配合Store.save(session)
不管是FileStore
還是JDBCStore
都是很簡單的,所以就不查看了。
除了getSession()
方法有不同的地方,周期性任務的方法也略有不同。
在ManagerBase
的backgroundProcess()
方法中:
@Override
public void backgroundProcess() {count = (count + 1) % processExpiresFrequency;if (count == 0)processExpires();
}
因為processExpires()
方法PersitentManagerBase
中有復寫的方法,所以會調用子類的方法。
@Override
public void processExpires() {//111111111long timeNow = System.currentTimeMillis();Session sessions[] = findSessions();int expireHere = 0 ;if(log.isDebugEnabled())log.debug("Start expire sessions " + getName() + " at " + timeNow + " sessioncount " + sessions.length);for (int i = 0; i < sessions.length; i++) {if (!sessions[i].isValid()) {expiredSessions.incrementAndGet();expireHere++;}}//222222processPersistenceChecks();if ((getStore() != null) && (getStore() instanceof StoreBase)) {((StoreBase) getStore()).processExpires();}long timeEnd = System.currentTimeMillis();if(log.isDebugEnabled())log.debug("End expire sessions " + getName() + " processingTime " + (timeEnd - timeNow) + " expired sessions: " + expireHere);processingTime += (timeEnd - timeNow);}
在標注1到標注2之間的代碼和之前查看的并無區別,基本就是將內存中的session一個個過期檢查下。接著調用了processPersistenceChecks()
方法。
public void processPersistenceChecks() {//空閑時間超出一定的存儲到存儲器中processMaxIdleSwaps();//活躍session超出一定比例的存儲到存儲器中processMaxActiveSwaps();//空閑時間超出一定時間的進行備份processMaxIdleBackups();
}
因為三個方法都相差不大,就著了其中一個來查看下
/*** Swap idle sessions out to Store if they are idle too long.*/
protected void processMaxIdleSwaps() {if (!getState().isAvailable() || maxIdleSwap < 0)return;//獲取所有的sessionSession sessions[] = findSessions();long timeNow = System.currentTimeMillis();// Swap out all sessions idle longer than maxIdleSwap//一個變量,在server.xml里可以配置,session的最大空閑時間,超出session會被保存到存儲器中,如果是負數,那么永遠不保存if (maxIdleSwap >= 0) {for (int i = 0; i < sessions.length; i++) {StandardSession session = (StandardSession) sessions[i];synchronized (session) {if (!session.isValid())continue;int timeIdle;if (StandardSession.LAST_ACCESS_AT_START) {timeIdle = (int) ((timeNow - session.getLastAccessedTimeInternal()) / 1000L);} else {timeIdle = (int) ((timeNow - session.getThisAccessedTimeInternal()) / 1000L);}if (timeIdle >= maxIdleSwap && timeIdle >= minIdleSwap) {if (session.accessCount != null &&session.accessCount.get() > 0) {// Session is currently being accessed - skip itcontinue;}if (log.isDebugEnabled())log.debug(sm.getString("persistentManager.swapMaxIdle",session.getIdInternal(),Integer.valueOf(timeIdle)));try {//11111swapOut(session);} catch (IOException e) {// This is logged in writeSession()}}}}}}
查看標注1 的 swapOut(session)
protected void swapOut(Session session) throws IOException {if (store == null || !session.isValid()) {return;}((StandardSession)session).passivate();//222//寫入到存儲器中writeSession(session);//從活躍session名單中移除,也就是內存中移除super.remove(session, true);//回收session對象session.recycle();}
查看標注2的writeSession()
protected void writeSession(Session session) throws IOException {if (store == null || !session.isValid()) {return;}try {if (SecurityUtil.isPackageProtectionEnabled()){try{AccessController.doPrivileged(new PrivilegedStoreSave(session));}catch(PrivilegedActionException ex){Exception exception = ex.getException();if (exception instanceof IOException) {throw (IOException) exception;}log.error("Exception in the Store during writeSession: "+ exception, exception);}} else {//3333333store.save(session);} } catch (IOException e) {log.error(sm.getString("persistentManager.serializeError", session.getIdInternal(), e));throw e;}}
可以看出最后還是調用的store.save(session)
方法,就不再查看了,其他的processMaxActiveSwaps()
,processMaxIdleBackups()
方法都很類似,就留給讀者自行查看了。
總的來說PersistentManager
與StandardManager
區別在于,PersistentManager
在StandardManager
的基礎上額外增加了存儲的功能,不管查找,刪除,還是保存都需要在內存和存儲器中同時進行。
總結:本文討論了session管理器,該組件用來管理session管理中的session對象,解釋了不同管理器的區別,以及session管理器如何把內存中session持久化到存儲器中
最后附上相關配置:
在web.xml
中配置 session 的過期時間,默認30min
<session-config><session-timeout>30</session-timeout>
</session-config>
在server.xml
中配置 session管理器,默認StandardManager
可以不配置,如果需要配置全局的session manager,可以在conf/context.xml
中配置
StandardManager
當Tomcat服務器關閉或重啟,或者Web應用被重新加載時,會對在內存中的HttpSession對象進行持久化, 并把它們保存到文件系統中,默認的文件為$CATALINA_HOME/work/Catalina/hostname/applicationname/SESSIONS.ser
在<Context></Context>
標簽內配置<Manager></Manager>
標簽
<Manager className="org.apache.catalina.session.StandardManager" maxInactiveInterval="-1" />
備注:如果服務器異常關閉則所有會話都會丟失,StandardManager
沒有機會進行存盤處理
PersistentManager
<Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="true"maxActiveSessions="-1"minIdleSwap="60"maxIdleSwap="60"maxIdleBackup="60"><!--<Store className="org.apache.catalina.session.FileStore" directory="../session" />--><Store className="org.apache.catalina.session.JDBCStore"driverName="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://url?user=user&password=psd"sessionTable="tomcat_session" sessionIdCol="session_id" sessionDataCol="session_data" sessionValidCol="session_valid" sessionMaxInactiveCol="max_inactive" sessionLastAccessedCol="last_access"sessionAppCol="app_name" />
</Manager>
saveOnRestart
:是否在重啟的時候加載保存sessionmaxActiveSessions
:最大允許session數量,-1 不限制minIdleSwap
:最小空閑時間,超出將會被轉存到存儲器中maxIdleSwap
:最大空閑時間,超出將會被轉存到存儲器中
Store
相關:
directory
:采用FileStore
的時候指存儲session的目錄sessionTable
:存儲session的表名sessionIdCol
:sessionid列名sessionDataCol
:sessionData列名sessionValidCol
:session是否有效列名sessionMaxInactiveCol
:session最大閑置時間列名sessionLastAccessedCol
:session上次訪問時間列名sessionAppCol
:session歸屬的應用名稱列名
(完)