Tomcat Session管理机制(Tomcat源码解析七)

前面几篇我们分析了Tomcat的启动,关闭,请求处理的流程,tomcat的classloader机制,本篇将接着分析Tomcat的session管理方面的内容。

在开始之前,我们先来看一下总体上的结构,熟悉了总体结构以后,我们在一步步的去分析源代码。Tomcat session相光的类图如下:

通过上图,我们可以看出每一个StandardContext会关联一个Manager,默认情况下Manager的实现类是StandardManager,而StandardManager内部会聚合多个Session,其中StandardSession是Session的默认实现类,当我们调用Request.getSession的时候,Tomcat通过StandardSessionFacade这个外观类将StandardSession包装以后返回。

上面清楚了总体的结构以后,我们来进一步的通过源代码来分析一下。咋们首先从Request的getSession方法看起。

[java]  view plain copy
  1. org.apache.catalina.connector.Request#getSession  

[java]  view plain copy
  1. public HttpSession getSession() {  
  2.     Session session = doGetSession(true);  
  3.     if (session == null) {  
  4.         return null;  
  5.     }  
  6.   
  7.     return session.getSession();  
  8. }  
从上面的代码,我们可以看出首先首先调用doGetSession方法获取Session,然后再调用Session的getSession方法返回HttpSession,那接下来我们再来看看doGetSession方法:

[java]  view plain copy
  1. org.apache.catalina.connector.Request#doGetSession  
  2. protected Session doGetSession(boolean create) {  
  3.   
  4.     // There cannot be a session if no context has been assigned yet  
  5.     if (context == null) {  
  6.         return (null);  
  7.     }  
  8.   
  9.     // Return the current session if it exists and is valid  
  10.     if ((session != null) && !session.isValid()) {  
  11.         session = null;  
  12.     }  
  13.     if (session != null) {  
  14.         return (session);  
  15.     }  
  16.   
  17.     // Return the requested session if it exists and is valid  
  18.     // 1   
  19.     Manager manager = null;  
  20.     if (context != null) {  
  21.         manager = context.getManager();  
  22.     }  
  23.     if (manager == null)  
  24.      {  
  25.         return (null);      // Sessions are not supported  
  26.     }  
  27.     // 2  
  28.     if (requestedSessionId != null) {  
  29.         try {  
  30.             session = manager.findSession(requestedSessionId);  
  31.         } catch (IOException e) {  
  32.             session = null;  
  33.         }  
  34.         if ((session != null) && !session.isValid()) {  
  35.             session = null;  
  36.         }  
  37.         if (session != null) {  
  38.             session.access();  
  39.             return (session);  
  40.         }  
  41.     }  
  42.   
  43.     // Create a new session if requested and the response is not committed  
  44.     // 3  
  45.     if (!create) {  
  46.         return (null);  
  47.     }  
  48.     if ((context != null) && (response != null) &&  
  49.         context.getServletContext().getEffectiveSessionTrackingModes().  
  50.                 contains(SessionTrackingMode.COOKIE) &&  
  51.         response.getResponse().isCommitted()) {  
  52.         throw new IllegalStateException  
  53.           (sm.getString("coyoteRequest.sessionCreateCommitted"));  
  54.     }  
  55.   
  56.     // Attempt to reuse session id if one was submitted in a cookie  
  57.     // Do not reuse the session id if it is from a URL, to prevent possible  
  58.     // phishing attacks  
  59.     // Use the SSL session ID if one is present.  
  60.     // 4  
  61.     if (("/".equals(context.getSessionCookiePath())  
  62.             && isRequestedSessionIdFromCookie()) || requestedSessionSSL ) {  
  63.         session = manager.createSession(getRequestedSessionId());  
  64.     } else {  
  65.         session = manager.createSession(null);  
  66.     }  
  67.   
  68.     // Creating a new session cookie based on that session  
  69.     if ((session != null) && (getContext() != null)  
  70.            && getContext().getServletContext().  
  71.                    getEffectiveSessionTrackingModes().contains(  
  72.                            SessionTrackingMode.COOKIE)) {  
  73.         // 5   
  74.         Cookie cookie =  
  75.             ApplicationSessionCookieConfig.createSessionCookie(  
  76.                     context, session.getIdInternal(), isSecure());  
  77.   
  78.         response.addSessionCookieInternal(cookie);  
  79.     }  
  80.   
  81.     if (session == null) {  
  82.         return null;  
  83.     }  
  84.   
  85.     session.access();  
  86.     return session;  
  87. }  

下面我们就来重点分析一下,上面代码中标注了数字的地方:

  1. 标注1(第17行)首先从StandardContext中获取对应的Manager对象,缺省情况下,这个地方获取的其实就是StandardManager的实例。
  2. 标注2(第26行)从Manager中根据requestedSessionId获取session,如果session已经失效了,则将session置为null以便下面创建新的session,如果session不为空则通过调用session的access方法标注session的访问时间,然后返回。
  3. 标注3(第43行)判断传递的参数,如果为false,则直接返回空,这其实就是对应的Request.getSession(true/false)的情况,当传递false的时候,如果不存在session,则直接返回空,不会新建。
  4. 标注4 (第59行)调用Manager来创建一个新的session,这里默认会调用到StandardManager的方法,而StandardManager继承了ManagerBase,那么默认其实是调用了了ManagerBase的方法。
  5. 标注5 (第72行)创建了一个Cookie,而Cookie的名称就是大家熟悉的JSESSIONID,另外JSESSIONID其实也是可以配置的,这个可以通过context节点的sessionCookieName来修改。比如….

通过doGetSession获取到Session了以后,我们发现调用了session.getSession方法,而Session的实现类是StandardSession,那么我们再来看下StandardSession的getSession方法。

[java]  view plain copy
  1. org.apache.catalina.session.StandardSession#getSession  
  2. public HttpSession getSession() {  
  3.   
  4.     if (facade == null){  
  5.         if (SecurityUtil.isPackageProtectionEnabled()){  
  6.             final StandardSession fsession = this;  
  7.             facade = AccessController.doPrivileged(  
  8.                     new PrivilegedAction<StandardSessionFacade>(){  
  9.                 @Override  
  10.                 public StandardSessionFacade run(){  
  11.                     return new StandardSessionFacade(fsession);  
  12.                 }  
  13.             });  
  14.         } else {  
  15.             facade = new StandardSessionFacade(this);  
  16.         }  
  17.     }  
  18.     return (facade);  
  19.   
  20. }  

通过上面的代码,我们可以看到通过StandardSessionFacade的包装类将StandardSession包装以后返回。到这里我想大家应该熟悉了Session创建的整个流程。

接着我们再来看看,Sesssion是如何被销毁的。我们在Tomcat启动过程(Tomcat源代码阅读系列之三)中之处,在容器启动以后会启动一个ContainerBackgroundProcessor线程,这个线程是在Container启动的时候启动的,这条线程就通过后台周期性的调用org.apache.catalina.core.ContainerBase#backgroundProcess,而backgroundProcess方法最终又会调用org.apache.catalina.session.ManagerBase#backgroundProcess,接下来我们就来看看Manger的backgroundProcess方法。


[java]  view plain copy
  1. org.apache.catalina.session.ManagerBase#backgroundProcess  
  2. public void backgroundProcess() {  
  3.     count = (count + 1) % processExpiresFrequency;  
  4.     if (count == 0)  
  5.         processExpires();  
  6. }  
上面的代码里,需要注意一下,默认情况下backgroundProcess是每10秒运行一次(StandardEngine构造的时候,将backgroundProcessorDelay设置为了10),而这里我们通过processExpiresFrequency来控制频率,例如processExpiresFrequency的值默认为6,那么相当于没一分钟运行一次processExpires方法。接下来我们再来看看processExpires。

[java]  view plain copy
  1. org.apache.catalina.session.ManagerBase#processExpires  
  2. public void processExpires() {  
  3.   
  4.     long timeNow = System.currentTimeMillis();  
  5.     Session sessions[] = findSessions();  
  6.     int expireHere = 0 ;  
  7.   
  8.     if(log.isDebugEnabled())  
  9.         log.debug("Start expire sessions " + getName() + " at " + timeNow + " sessioncount " + sessions.length);  
  10.     for (int i = 0; i < sessions.length; i++) {  
  11.         if (sessions[i]!=null && !sessions[i].isValid()) {  
  12.             expireHere++;  
  13.         }  
  14.     }  
  15.     long timeEnd = System.currentTimeMillis();  
  16.     if(log.isDebugEnabled())  
  17.          log.debug("End expire sessions " + getName() + " processingTime " + (timeEnd - timeNow) + " expired sessions: " + expireHere);  
  18.     processingTime += ( timeEnd - timeNow );  
  19.   
  20. }  
上面的代码比较简单,首先查找出当前context的所有的session,然后调用session的isValid方法,接下来我们在看看Session的isValid方法。

[java]  view plain copy
  1. org.apache.catalina.session.StandardSession#isValid  
  2. public boolean isValid() {  
  3.   
  4.     if (this.expiring) {  
  5.         return true;  
  6.     }  
  7.   
  8.     if (!this.isValid) {  
  9.         return false;  
  10.     }  
  11.   
  12.     if (ACTIVITY_CHECK && accessCount.get() > 0) {  
  13.         return true;  
  14.     }  
  15.   
  16.     if (maxInactiveInterval > 0) {  
  17.         long timeNow = System.currentTimeMillis();  
  18.         int timeIdle;  
  19.         if (LAST_ACCESS_AT_START) {  
  20.             timeIdle = (int) ((timeNow - lastAccessedTime) / 1000L);  
  21.         } else {  
  22.             timeIdle = (int) ((timeNow - thisAccessedTime) / 1000L);  
  23.         }  
  24.         if (timeIdle >= maxInactiveInterval) {  
  25.             expire(true);  
  26.         }  
  27.     }  
  28.   
  29.     return (this.isValid);  
  30. }  

查看上面的代码,主要就是通过对比当前时间和上次访问的时间差是否大于了最大的非活动时间间隔,如果大于就会调用expire(true)方法对session进行超期处理。这里需要注意一点,默认情况下LAST_ACCESS_AT_START为false,读者也可以通过设置系统属性的方式进行修改,而如果采用LAST_ACCESS_AT_START的时候,那么请求本身的处理时间将不算在内。比如一个请求处理开始的时候是10:00,请求处理花了1分钟,那么如果LAST_ACCESS_AT_START为true,则算是否超期的时候,是从10:00算起,而不是10:01。

接下来我们再来看看expire方法,代码如下:

[java]  view plain copy
  1. org.apache.catalina.session.StandardSession#expire  
  2. public void expire(boolean notify) {  
  3.   
  4.     // Check to see if expire is in progress or has previously been called  
  5.     if (expiring || !isValid)  
  6.         return;  
  7.   
  8.     synchronized (this) {  
  9.         // Check again, now we are inside the sync so this code only runs once  
  10.         // Double check locking - expiring and isValid need to be volatile  
  11.         if (expiring || !isValid)  
  12.             return;  
  13.   
  14.         if (manager == null)  
  15.             return;  
  16.   
  17.         // Mark this session as "being expired"  
  18.         // 1           
  19.         expiring = true;  
  20.   
  21.         // Notify interested application event listeners  
  22.         // FIXME - Assumes we call listeners in reverse order  
  23.         Context context = (Context) manager.getContainer();  
  24.   
  25.         // The call to expire() may not have been triggered by the webapp.  
  26.         // Make sure the webapp's class loader is set when calling the  
  27.         // listeners  
  28.         ClassLoader oldTccl = null;  
  29.         if (context.getLoader() != null &&  
  30.                 context.getLoader().getClassLoader() != null) {  
  31.             oldTccl = Thread.currentThread().getContextClassLoader();  
  32.             if (Globals.IS_SECURITY_ENABLED) {  
  33.                 PrivilegedAction<Void> pa = new PrivilegedSetTccl(  
  34.                         context.getLoader().getClassLoader());  
  35.                 AccessController.doPrivileged(pa);  
  36.             } else {  
  37.                 Thread.currentThread().setContextClassLoader(  
  38.                         context.getLoader().getClassLoader());  
  39.             }  
  40.         }  
  41.         try {  
  42.             // 2  
  43.             Object listeners[] = context.getApplicationLifecycleListeners();  
  44.             if (notify && (listeners != null)) {  
  45.                 HttpSessionEvent event =  
  46.                     new HttpSessionEvent(getSession());  
  47.                 for (int i = 0; i < listeners.length; i++) {  
  48.                     int j = (listeners.length - 1) - i;  
  49.                     if (!(listeners[j] instanceof HttpSessionListener))  
  50.                         continue;  
  51.                     HttpSessionListener listener =  
  52.                         (HttpSessionListener) listeners[j];  
  53.                     try {  
  54.                         context.fireContainerEvent("beforeSessionDestroyed",  
  55.                                 listener);  
  56.                         listener.sessionDestroyed(event);  
  57.                         context.fireContainerEvent("afterSessionDestroyed",  
  58.                                 listener);  
  59.                     } catch (Throwable t) {  
  60.                         ExceptionUtils.handleThrowable(t);  
  61.                         try {  
  62.                             context.fireContainerEvent(  
  63.                                     "afterSessionDestroyed", listener);  
  64.                         } catch (Exception e) {  
  65.                             // Ignore  
  66.                         }  
  67.                         manager.getContainer().getLogger().error  
  68.                             (sm.getString("standardSession.sessionEvent"), t);  
  69.                     }  
  70.                 }  
  71.             }  
  72.         } finally {  
  73.             if (oldTccl != null) {  
  74.                 if (Globals.IS_SECURITY_ENABLED) {  
  75.                     PrivilegedAction<Void> pa =  
  76.                         new PrivilegedSetTccl(oldTccl);  
  77.                     AccessController.doPrivileged(pa);  
  78.                 } else {  
  79.                     Thread.currentThread().setContextClassLoader(oldTccl);  
  80.                 }  
  81.             }  
  82.         }  
  83.   
  84.         if (ACTIVITY_CHECK) {  
  85.             accessCount.set(0);  
  86.         }  
  87.         setValid(false);  
  88.   
  89.         // Remove this session from our manager's active sessions  
  90.         // 3   
  91.         manager.remove(thistrue);  
  92.   
  93.         // Notify interested session event listeners  
  94.         if (notify) {  
  95.             fireSessionEvent(Session.SESSION_DESTROYED_EVENT, null);  
  96.         }  
  97.   
  98.         // Call the logout method  
  99.         if (principal instanceof GenericPrincipal) {  
  100.             GenericPrincipal gp = (GenericPrincipal) principal;  
  101.             try {  
  102.                 gp.logout();  
  103.             } catch (Exception e) {  
  104.                 manager.getContainer().getLogger().error(  
  105.                         sm.getString("standardSession.logoutfail"),  
  106.                         e);  
  107.             }  
  108.         }  
  109.   
  110.         // We have completed expire of this session  
  111.         expiring = false;  
  112.   
  113.         // Unbind any objects associated with this session  
  114.         // 4  
  115.         String keys[] = keys();  
  116.         for (int i = 0; i < keys.length; i++)  
  117.             removeAttributeInternal(keys[i], notify);  
  118.   
  119.     }  
  120.   
  121. }  

上面代码的主流程我已经标注了数字,我们来逐一分析一下:

  1. 标注1(第18行)标记当前的session为超期
  2. 标注2(第41行)出发HttpSessionListener监听器的方法。
  3. 标注3(第89行)从Manager里面移除当前的session
  4. 标注4(第113行)将session中保存的属性移除。

到这里我们已经清楚了Tomcat中对与StandardSession的创建以及销毁的过程,其实StandardSession仅仅是实现了内存中Session的存储,而Tomcat还支持将Session持久化,以及Session集群节点间的同步。这些内容我们以后再来分析。








版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值