Tomcat的Session管理(三)

摘要:PersistentManagerStandardManager的異同。

之前兩篇關于session的文章主要討論了session相關的創建、查詢、過期處理。而我們查看源碼的時候都是默認實現是StandardManager類,實際上實現也可以是PersistentManager類,下面我們就查看下該類的相關方法。

我們都知道PersistentManager代表的是持久化session的管理器。在PersistentManager類定義中有個變量org.apache.catalina.Store,該變量表示session管理器持久化session的方式,具體類圖如下:

818454-20161205165908351-2096649172.jpg

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類相關方法。

RequestdoGetSession()方法中,我們之前默認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()方法有不同的地方,周期性任務的方法也略有不同。

ManagerBasebackgroundProcess()方法中:

    @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()方法都很類似,就留給讀者自行查看了。

總的來說PersistentManagerStandardManager區別在于,PersistentManagerStandardManager的基礎上額外增加了存儲的功能,不管查找,刪除,還是保存都需要在內存和存儲器中同時進行。

總結:本文討論了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&amp;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:是否在重啟的時候加載保存session
  • maxActiveSessions:最大允許session數量,-1 不限制
  • minIdleSwap:最小空閑時間,超出將會被轉存到存儲器中
  • maxIdleSwap:最大空閑時間,超出將會被轉存到存儲器中

Store相關:

  • directory:采用FileStore的時候指存儲session的目錄
  • sessionTable:存儲session的表名
  • sessionIdCol:sessionid列名
  • sessionDataCol:sessionData列名
  • sessionValidCol:session是否有效列名
  • sessionMaxInactiveCol:session最大閑置時間列名
  • sessionLastAccessedCol:session上次訪問時間列名
  • sessionAppCol:session歸屬的應用名稱列名

(完)

轉載于:https://www.cnblogs.com/coldridgeValley/p/6096143.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/456884.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/456884.shtml
英文地址,請注明出處:http://en.pswp.cn/news/456884.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

計算機基礎的函數公式,大學計算機基礎 excle 公式與函數

《大學計算機基礎 excle 公式與函數》由會員分享&#xff0c;可在線閱讀&#xff0c;更多相關《大學計算機基礎 excle 公式與函數(32頁珍藏版)》請在人人文庫網上搜索。1、,.,場景1,發布日期:2011.11.09,新入職場,經理說&#xff1a; 小張&#xff0c;以后工資發放的事情就交給…

穩定和性能如何兼顧?58大數據平臺的技術演進與實踐

作者&#xff5c;趙健博 編輯&#xff5c;尚劍 本文將為你分享58大數據平臺在最近一年半內技術演進的過程&#xff0c;包括&#xff1a;58大數據平臺目前的整體架構是怎么樣的&#xff1b;最近一年半的時間內我們面臨的問題、挑戰以及技術演進過程&#xff1b;以及未來的規劃。…

Random Forest算法簡介

轉自JoinQuant量化課堂 一、相關概念 分類器&#xff1a;分類器就是給定一個樣本的數據&#xff0c;判定這個樣本屬于哪個類別的算法。例如在股票漲跌預測中&#xff0c;我們認為前一天的交易量和收盤價對于第二天的漲跌是有影響的&#xff0c;那么分類器就是通過樣本的交易量…

MySQL 學習筆記

01 import pymysql#連接數據庫db pymysql.connect("192.168.1.179","root","liuwang","liu")#創建一個cursor對象 cursor db.cursor() sql "select version()"cursor.execute(sql)data cursor.fetchone() print(data)…

簡單交互

控件有著各種事件&#xff0c;例如被點擊的時候&#xff0c;我們可以在事件里面添加動作和命令&#xff0c;讓控件可以和用戶交互&#xff0c;這里我們演示一個簡單的交互&#xff1a;當用戶點擊文字控件的時候&#xff0c;它開始動畫向下移動然后動畫旋轉&#xff0c;效果入下…

綜合素質計算機考點,教師資格證小學綜合素質考點及考試真題:信息處理能力...

小學綜合素質考點及考試真題——信息處理能力大綱要求&#xff1a;具有運用工具書檢索信息、資料的能力。具有運用網絡檢索、交流信息的能力。具有對信息進行篩選、分類、存儲和應用的能力。具有運用教育測量知識進行數據分析與處理的能力。具有根據教育教學的需要&#xff0c;…

API文檔自動生成

本文主要講述自動化API文檔生成——apidoc。網上有幾個篇文章都只是介紹apidoc的&#xff0c;具體怎么在自己的項目中使用以及與其他配合使用都是沒介紹的。最近開始玩服務器&#xff0c;了解到了有Windows與Linux之間共享文件的方法&#xff0c;就是samba。然后具體和apidoc結…

機器學習筆記之SVM(SVR)算法

學過SVM后&#xff0c;看了那么多別人的文章&#xff0c;是時候自己總結一波了。權當寫的筆記供自己日后再回顧吧。 PS:結合自己在工作過程中&#xff08;我這里用SVR做股票預測&#xff09;用到的知識來寫的&#xff0c;不會很全面&#xff0c;若有些知識這里沒提及讀者可自行…

[轉]基于圖的機器學習技術:谷歌眾多產品和服務背后的智能

近來機器學習領域實現了很多重大的進展&#xff0c;這些進展讓計算機系統具備了解決復雜的真實世界問題的能力。其中&#xff0c;谷歌的機器學習又是怎樣的 &#xff1f; 近來機器學習領域實現了很多重大的進展&#xff0c;這些進展讓計算機系統具備了解決復雜的真實世界問題的…

安裝mysql后在安裝目錄下只有my-default.ini沒有my.ini文件 解決-The MySQL server is running with the --secure-file-priv

WIN10 系統環境 安裝mysql后在安裝目錄下只有my-default.ini沒有my.ini文件 。 mysql報錯 ---------- The MySQL server is running with the --secure-file-priv option so it cannot execute this statement -------- 但是更改或想要查找配置文件就需要如下操作 在 安裝…

loewe測試軟件,實測Loewe三角包 最輕的小包最貼心的設計

原標題&#xff1a;實測Loewe三角包 最輕的小包最貼心的設計導語&#xff1a;每周一期的“包治百病”又跟大家見面來啦&#xff01;“包治百病”全方位評測包包的容量、重量、背法、在不同身高妹子身上的效果、各種驚人的小細節以及可能存在的問題&#xff0c;為有意購買這些包…

hadoop集群的搭建(分布式安裝)

集群 計算機集群是一種計算機系統&#xff0c;他通過一組松散集成的計算機軟件和硬件連接起來高度緊密地協同完成計算工作。集群系統中的單個計算機通常稱為節點&#xff0c;通常通過局域網連接。集群技術的特點&#xff1a;1、通過多臺計算機完成同一個工作。達到更高的效率 2…

解決:Error establishing a database connection阿里云修改數據庫密碼

今天閑來無事想把所有的二級密碼改成一致的&#xff0c;所以就把阿里云的mysql數據庫的密碼改了&#xff0c;結果&#xff0c;打開頁面報錯了&#xff0c;下邊的截圖是我問題解決后&#xff0c;重新復現的。如果修復這個問題后wordpress登錄頁面白板&#xff0c;此時不要著急&a…

機器學習各算法思想(極簡版)

讀到的一篇不錯的文章&#xff0c;拿來和大家分享一下。 轉自–頭條公眾號–極數蝸牛 &#xff08;1&#xff09;線性回歸 回歸最早是由高爾頓研究子女身高與父母身高遺傳關系提出的&#xff0c;發現子女平均身高總是向中心回歸而得名。其實“一分辛苦一分才”中就蘊含了線性…

PAT A 1118. Birds in Forest (25)【并查集】

并查集合并 #include<iostream> using namespace std; const int MAX 10010; int father[MAX],root[MAX]; int findfather(int x){if(xfather[x]) return x;else{int Ffindfather(father[x]);father[x]F;return F;} } void Union(int a , int b){int faAfindfather(a);i…

斯坦福計算機錄取難嗎,申請斯坦福究竟有多難? 什么樣條件的人才能被斯坦福錄取?斯坦福大學直播!...

原標題&#xff1a;申請斯坦福究竟有多難&#xff1f; 什么樣條件的人才能被斯坦福錄取&#xff1f;斯坦福大學直播&#xff01;申請斯坦福究竟有多難&#xff1f; 什么樣條件的人才能被斯坦福錄取&#xff1f;斯坦福大學直播&#xff01;西海岸小哈佛之稱的斯坦福大學&#xf…

解決:building 'twisted.test.raiser' extension安裝scrapy報錯

解決&#xff1a;building twisted.test.raiser extension error: Microsoft Visual C 14.0 is required. Get it with "Microsoft Visual C Build Tools": https://visualstudio.microsoft.com/downloads/ 安裝scrapy報錯&#xff0c;在Twisted安裝部分 解決方案…

Linux配置網絡出現Eroor adding default gateway的解決方案

最近在學習有關大數據方面的東西&#xff0c;剛開始要搭建模擬的虛擬機集群。用的是Minimal CentOS6.7版本Linux下的系統。因為我要為各個虛擬機設置靜態IP&#xff0c;所以就參考網上博客說的進行如下操作: 一、安裝完系統后先配置網絡&#xff1a; cd /etc/sysconfig/netwo…

揭秘8大自媒體平臺注冊方法,通過率百分之九十

寫在前面&#xff1a;準備材料&#xff1a;手機號&#xff0c;郵箱&#xff0c;手持照&#xff0c;輔助材料(非必選項)&#xff0c;邀請碼(非必選項)。輔助材料萬能公式&#xff1a;方法①新浪博客16級博客發8篇相關的文章&#xff0c;昵稱、描述、頭像都與所注冊自媒體號對應&…

AC日記——簡單密碼 openjudge 1.7 10

10:簡單密碼 總時間限制: 1000ms內存限制: 65536kB描述Julius Caesar曾經使用過一種很簡單的密碼。對于明文中的每個字符&#xff0c;將它用它字母表中后5位對應的字符來代替&#xff0c;這樣就得到了密文。比如字符A用F來代替。如下是密文和明文中字符的對應關系。密文A B C D…