当前位置: 首页 > 编程文章 >

Spring Session简介及实现原理源码分析

Spring Session简介及实现原理源码分析

作者:林川时间:2026-09-30 11:19:45浏览:416

Spring Session通过自定义Filter拦截请求,重写HttpServletRequest以透明替换HttpSession实现,支持将Session数据持久化至Redis、MongoDB等多种第三方存储。本文详细解析其解决集群Session共享问题的核心架构、集成步骤及关键源码逻辑,帮助开发者快速理解并应用该框架。

本文目录展开

Spring Session简介与核心功能

一:Spring Session介绍

1. 简介

在分布式集群环境中,Session共享始终是一个棘手的问题。以往通常依赖Servlet容器层面的解决方案,例如Tomcat提供的tomcat-redis-session-manager或memcached-session-manager等开源组件。

另一种常见做法是利用Nginx等负载均衡器配置ip_hash策略,将同一用户的请求固定路由到特定服务器节点上。

然而,上述两种传统方案均存在明显的局限性。


spring-session是spring旗下的一个项目,把servlet容器实现的httpSession替换为spring-session,专注于解决 session管理问题。可简单快速且无缝的集成到我们的应用中。

2. 支持功能

首先,框架允许轻松地将Session数据存储到第三方容器中,内置支持Redis、JVM内存Map、MongoDB、GemFire、Hazelcast以及JDBC等多种存储方式。

其次,针对同一浏览器访问同一网站需维持多个独立Session的场景提供了支持。

此外,框架兼容Restful API风格,不再强制依赖Cookie,可通过HTTP Header传递JSESSIONID来实现会话追踪。

最后,Spring Session能与WebSocket结合,实现生命周期的同步管理。

3. 集成方式

集成过程十分简便,具体可参考官网的samplesandguide文档:http://docs.spring.io/spring-session/docs/1.3.0.RELEASE/reference/html5/

主要集成步骤如下:

第一步,引入必要的依赖JAR包。

第二步,通过注解或XML方式配置特定的存储容器,例如配置Redis的XML连接信息。


  
/** 初始化一切spring-session准备,且把springSessionFilter放入IOC     **/
  
/** 这是存储容器的链接池 **/ 

第三步,在web.xml中通过XML方式配置Spring Session Filter,将其加入过滤器链(Filter Chain)。



     springSessionRepositoryFilter
     org.springframework.web.filter.DelegatingFilterProxy 
    
   
     springSessionRepositoryFilter
     /*
     REQUESTERROR 
   

Spring Session内部实现原理剖析

二:Spring Session框架内部剖析

1. 框架高层抽象结构图

2. Spring Session重写Servlet Request及Redis存储相关问题

Spring Session能够无缝替换应用服务器的Request对象,其大致原理如下: 1. 自定义一个Filter,并重写doFilter方法。 2. 继承HttpServletRequestWrapper和HttpServletResponseWrapper类,重写getSession等相关方法,在这些方法内部调用相应的Session存储容器操作类。 3. 在第一步的doFilter方法中,实例化第二步自定义的Request和Response类,并将它们传递给过滤器链。 4. 将该Filter配置在过滤器链的第一个位置。


/** 这个类是spring-session的1.30源码,也是实现上面第一到第三步的关键类 **/
public class SessionRepositoryFilter
    extends OncePerRequestFilter {

  /** session存储容器接口,redis、mongoDB、genfire等数据库都是实现该接口 **/
  private final SessionRepository sessionRepository;

  private ServletContext servletContext;
  /** 
   sessionID的传递方式接口。目前spring-session自带两个实现类
   1.cookie方式 :CookieHttpSessionStrategy
   2.http header 方式:HeaderHttpSessionStrategy
   当然,我们也可以自定义其他方式。
  **/
  private MultiHttpSessionStrategy httpSessionStrategy = new CookieHttpSessionStrategy();

  public SessionRepositoryFilter(SessionRepository sessionRepository) {
    if (sessionRepository == null) {
      throw new IllegalArgumentException("sessionRepository cannot be null");
    }
    this.sessionRepository = sessionRepository;
  }


  public void setHttpSessionStrategy(HttpSessionStrategy httpSessionStrategy) {
    if (httpSessionStrategy == null) {
      throw new IllegalArgumentException("httpSessionStrategy cannot be null");
    }
    /** 
    通过前面的spring-session功能介绍,我们知道spring-session可以支持单浏览器多
    session, 就是通过MultiHttpSessionStrategyAdapter来实现的。
    每个浏览器拥有一个sessionID,但是这个sessionID拥有多个别名(根据浏览器的tab)。如:
        别名1 sessionID
        别名2 sessionID
        ...
        而这个别名通过url来传递,这就是单浏览器多session原理了
        **/
    this.httpSessionStrategy = new MultiHttpSessionStrategyAdapter(
        httpSessionStrategy);
  }


  public void setHttpSessionStrategy(MultiHttpSessionStrategy httpSessionStrategy) {
    if (httpSessionStrategy == null) {
      throw new IllegalArgumentException("httpSessionStrategy cannot be null");
    }
    this.httpSessionStrategy = httpSessionStrategy;
  }
   /**
  该方法相当于重写了doFilter,只是spring-session又做了多一层封装。
  在这个方法里创建自定义的 request和response,然后传递到过滤器链filterChain
   **/
  @Override
  protected void doFilterInternal(HttpServletRequest request,
      HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    request.setAttribute(SESSION_REPOSITORY_ATTR, this.sessionRepository);
        /**
        spring-session重写的ServletRequest。这个类继承了HttpServletRequestWrapper 
        **/
    SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(
        request, response, this.servletContext);
    SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(
        wrappedRequest, response);

    HttpServletRequest strategyRequest = this.httpSessionStrategy
        .wrapRequest(wrappedRequest, wrappedResponse);
    HttpServletResponse strategyResponse = this.httpSessionStrategy
        .wrapResponse(wrappedRequest, wrappedResponse);

    try { 
       /** 
       传递自定义 request和response到链中,想象下如果
       该spring-sessionFilter位于过滤器链的第一个,那么后续的Filter,
       以及到达最后的控制层所获取的 request和response,是不是就是我们自定义的了?
       **/
      filterChain.doFilter(strategyRequest, strategyResponse);
    }
    finally {
      wrappedRequest.commitSession();
    }
  }

  public void setServletContext(ServletContext servletContext) {
    this.servletContext = servletContext;
  }

  /**
  这个就是Servlet response的重写类了
   */
  private final class SessionRepositoryResponseWrapper
      extends OnCommittedResponseWrapper {

    private final SessionRepositoryRequestWrapper request;


    SessionRepositoryResponseWrapper(SessionRepositoryRequestWrapper request,
        HttpServletResponse response) {
      super(response);
      if (request == null) {
        throw new IllegalArgumentException("request cannot be null");
      }
      this.request = request;
    }
     /** 
      这步是持久化session到存储容器,我们可能会在一个控制层里多次调用session的操作方法
      如果我们每次对session的操作都持久化到存储容器,必定会带来性能的影响。比如redis
      所以我们可以在整个控制层执行完毕了,response返回信息到浏览器时,才持久化session
     **/
    @Override
    protected void onResponseCommitted() {
      this.request.commitSession();
    }
  }

  /**
  spring-session 的request重写类,这几乎是最重要的一个重写类。里面重写了获取getSession,Session等方法以及类
   */
  private final class SessionRepositoryRequestWrapper
      extends HttpServletRequestWrapper {
    private Boolean requestedSessionIdValid;
    private boolean requestedSessionInvalidated;
    private final HttpServletResponse response;
    private final ServletContext servletContext;

    private SessionRepositoryRequestWrapper(HttpServletRequest request,
        HttpServletResponse response, ServletContext servletContext) {
      super(request);
      this.response = response;
      this.servletContext = servletContext;
    }

    /**
     * Uses the HttpSessionStrategy to write the session id to the response and
     * persist the Session.
     */
    private void commitSession() {
      HttpSessionWrapper wrappedSession = getCurrentSession();
      if (wrappedSession == null) {
          // session失效,删除cookie或者header
        if (isInvalidateClientSession()) {
          SessionRepositoryFilter.this.httpSessionStrategy
              .onInvalidateSession(this, this.response);
        }
      }
      else {
        S session = wrappedSession.getSession();
        SessionRepositoryFilter.this.sessionRepository.save(session);
        if (!isRequestedSessionIdValid()
            || !session.getId().equals(getRequestedSessionId())) {
        // 把cookie或者header写回给浏览器保存 
        SessionRepositoryFilter.this.httpSessionStrategy.onNewSession(session,
              this, this.response);
        }
      }
    }

    @SuppressWarnings("unchecked")
    private HttpSessionWrapper getCurrentSession() {
      return (HttpSessionWrapper) getAttribute(CURRENT_SESSION_ATTR);
    }

    private void setCurrentSession(HttpSessionWrapper currentSession) {
      if (currentSession == null) {
        removeAttribute(CURRENT_SESSION_ATTR);
      }
      else {
        setAttribute(CURRENT_SESSION_ATTR, currentSession);
      }
    }

    @SuppressWarnings("unused")
    public String changeSessionId() {
      HttpSession session = getSession(false);

      if (session == null) {
        throw new IllegalStateException(
            "Cannot change session ID. There is no session associated with this request.");
      }

      // eagerly get session attributes in case implementation lazily loads them
      Map attrs = new HashMap();
      Enumeration iAttrNames = session.getAttributeNames();
      while (iAttrNames.hasMoreElements()) {
        String attrName = iAttrNames.nextElement();
        Object value = session.getAttribute(attrName);

        attrs.put(attrName, value);
      }

      SessionRepositoryFilter.this.sessionRepository.delete(session.getId());
      HttpSessionWrapper original = getCurrentSession();
      setCurrentSession(null);

      HttpSessionWrapper newSession = getSession();
      original.setSession(newSession.getSession());

      newSession.setMaxInactiveInterval(session.getMaxInactiveInterval());
      for (Map.Entry attr : attrs.entrySet()) {
        String attrName = attr.getKey();
        Object attrValue = attr.getValue();
        newSession.setAttribute(attrName, attrValue);
      }
      return newSession.getId();
    }
    // 判断session是否有效
    @Override
    public boolean isRequestedSessionIdValid() {
      if (this.requestedSessionIdValid == null) {
        String sessionId = getRequestedSessionId();
        S session = sessionId == null ? null : getSession(sessionId);
        return isRequestedSessionIdValid(session);
      }

      return this.requestedSessionIdValid;
    }

    private boolean isRequestedSessionIdValid(S session) {
      if (this.requestedSessionIdValid == null) {
        this.requestedSessionIdValid = session != null;
      }
      return this.requestedSessionIdValid;
    }

    private boolean isInvalidateClientSession() {
      return getCurrentSession() == null && this.requestedSessionInvalidated;
    }

    private S getSession(String sessionId) {
       // 从session存储容器中根据sessionID获取session
      S session = SessionRepositoryFilter.this.sessionRepository
          .getSession(sessionId);
      if (session == null) {
        return null;
      }
      // 设置sesison的最后访问时间,以防过期
      session.setLastAccessedTime(System.currentTimeMillis());
      return session;
    }
     /**
     这个方法是不是很熟悉,下面还有个getSession()才更加熟悉。没错,就是在这里重新获取session方法 
     **/
    @Override
    public HttpSessionWrapper getSession(boolean create) {
      //快速获取session,可以理解为一级缓存、二级缓存这种关系
      HttpSessionWrapper currentSession = getCurrentSession();
      if (currentSession != null) {
        return currentSession;
      }
      //从httpSessionStratge里面根据cookie或者header获取sessionID
      String requestedSessionId = getRequestedSessionId();
      if (requestedSessionId != null
          && getAttribute(INVALID_SESSION_ID_ATTR) == null) {                                           
        //从存储容器获取session以及设置当次初始化属性                      
        S session = getSession(requestedSessionId);
        if (session != null) {
          this.requestedSessionIdValid = true;
          currentSession = new HttpSessionWrapper(session, getServletContext());
          currentSession.setNew(false);
          setCurrentSession(currentSession);
          return currentSession;
        }
        else {

          if (SESSION_LOGGER.isDebugEnabled()) {
            SESSION_LOGGER.debug(
                "No session found by id: Caching result for getSession(false) for this HttpServletRequest.");
          }
          setAttribute(INVALID_SESSION_ID_ATTR, "true");
        }
      }
      if (!create) {
        return null;
      }
      if (SESSION_LOGGER.isDebugEnabled()) {
        SESSION_LOGGER.debug(
            "A new session was created. To help you troubleshoot where the session was created we provided a StackTrace (this is not an error). You can prevent this from appearing by disabling DEBUG logging for "
                + SESSION_LOGGER_NAME,
            new RuntimeException(
                "For debugging purposes only (not an error)"));
      }
      // 如果该浏览器或者其他http访问者是初次访问服务器,则为他创建个新的session
      S session = SessionRepositoryFilter.this.sessionRepository.createSession();
      session.setLastAccessedTime(System.currentTimeMillis());
      currentSession = new HttpSessionWrapper(session, getServletContext());
      setCurrentSession(currentSession);
      return currentSession;
    }

    @Override
    public ServletContext getServletContext() {
      if (this.servletContext != null) {
        return this.servletContext;
      }
      // Servlet 3.0+
      return super.getServletContext();
    }

    @Override
    public HttpSessionWrapper getSession() {
      return getSession(true);
    }

    @Override
    public String getRequestedSessionId() {
      return SessionRepositoryFilter.this.httpSessionStrategy
          .getRequestedSessionId(this);
    }

    /**
    HttpSession的重写类
     */
    private final class HttpSessionWrapper extends ExpiringSessionHttpSession {

      HttpSessionWrapper(S session, ServletContext servletContext) {
        super(session, servletContext);
      }

      @Override
      public void invalidate() {
        super.invalidate();
        SessionRepositoryRequestWrapper.this.requestedSessionInvalidated = true;
        setCurrentSession(null);
        SessionRepositoryFilter.this.sessionRepository.delete(getId());
      }
    }
  }
}

总结

以上就是本文关于Spring Session简介及实现原理源码分析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出!

上一篇
Apache虚拟主机配置与Rewrite模块环境变量详解

本文介绍在Ubuntu系统中配置Apache虚拟主机的完整流程,包括创建配置文件、激活站点、重启服务及设置hosts文件。同时详细解析Apache提供给rewrite模块的五类服务器环境变量,涵盖HTTP头部、服务器内部信息、连接请求、时间日期及特殊变量,并列出对应PHP $_SERVER参数的映射关系,便于开发者进行URL重写和访问控制。

下一篇
Spring Boot Session超时机制原理与配置详解

本文解析Spring Boot中Session超时的默认机制、配置方法及底层判断逻辑。通过debug发现默认超时时间为1800秒,该值源自ServerProperties类中的sessionTimeout参数。系统启动时,该参数经AbstractConfigurableEmbeddedServletContainer处理并传递给Tomcat的MaxInactiveInterval。用户可在application.yml中通过server.session.timeout自定义超时时间(单位秒),非60整数倍将向上取整。超时判断基于请求间隔是否超过该阈值。

相关文章

更多
PHP配置Memcache存储Session详解

本文介绍如何在PHP中配置Memcache作为Session存储后端,以解决多Web服务器环境下的Session共享问题。通过修改php.ini、.htaccess或代码中的ini_set函数,可指定Memcache服务器地址及参数。同时涵盖Memcached服务的启动命令、参数说明,以及针对高并发场景的缓存策略与性能优化建议,如本地缓存前置和哈希分片等。

2026.02.15 987
Yii框架Session操作指南:配置、读写与销毁

在Yii框架中,autoStart属性默认为true,无需调用session_start()即可通过$_SESSION或封装对象访问会话数据。本文介绍如何设置、读取和移除Session变量,展示如何在main.php中配置自定义参数及将Session持久化至数据库,并提供获取当前Session ID及用户登出时彻底清除服务器端数据的完整方法。

2025.11.19 987
PHP中精确设置Session过期时间与失效处理方案

本文详解PHP中Session过期时间的配置机制与常见失效问题的解决方案。通过修改php.ini中的session.gc_maxlifetime、session.cookie_lifetime等参数,可精确控制服务端与客户端的Session生命周期。针对无权限修改配置文件或Session无法传递的情况,提供了利用session_id()、调整output_buffering及自定义session_save_path等代码级替代方案,确保Session在不同环境下的稳定运行。

2026.03.22 952
Laravel无法获取Session的三种解决方案

在Laravel开发中,若使用全局函数session()能保存数据却无法获取,通常由中间件缺失或请求提前终止导致。首先需确保路由注册在web中间件组下以启动Session服务;其次检查路由定义语法是否正确应用了中间件;最后注意不要在Controller或View中直接调用exit或die,否则将跳过Session的自动保存流程,应改用return返回响应。

2025.02.24 951
PHP引用计数器与Session垃圾回收机制详解

PHP通过引用计数器实现自动垃圾收集,当对象引用数为零时从内存中移除。在面向对象编程中,需显式销毁对象以防内存溢出。对于Session管理,PHP基于session.gc_probability和session.gc_divisor概率触发GC进程,扫描并删除超过session.gc_maxlifetime时限的文件。多站点环境下建议独立存储路径以避免冲突。

2025.01.21 928
PHP修改SESSION生存时间的两种方法及回收机制详解

本文介绍如何在PHP中通过代码和配置文件修改Session的生存时间。详细解析了session_set_cookie_params函数用法、php.ini中gc_maxlifetime参数的作用,以及Session垃圾回收(Garbage Collection)的工作原理和潜在问题解决方案。

2026.06.13 919

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。