Insight spring-session 配置

来源:互联网 发布:windows找不到cdm 编辑:程序博客网 时间:2024/05/22 02:28

spring-session 项目实现了redis、jdbc、gemfire 版本的分布式httpsession。

启用方式分为注解、xml配置。

原理就是配置filter,代理原有的httpsession的生成、获取、销毁的实现。

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


那么,这个filter是如何工作的?

从DelegatingFilterProxy入口,WebApplicationContext.getBean() 的方式获取到我们需要的x-httpsession实现。

/** * 此处的 delegateToUse就是分布式httpsession的bean * doFilter过程中进行初始化check    (漂亮的代码随处可见啊) * 然后将分布式httpsession加入请求的filterChain, 达到httpsession代理的目的 **/public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {    // Lazily initialize the delegate if necessary.    Filter delegateToUse = this.delegate;    if (delegateToUse == null) {        synchronized (this.delegateMonitor) {            if (this.delegate == null) {                WebApplicationContext wac = findWebApplicationContext();                if (wac == null) {                    throw new IllegalStateException("No WebApplicationContext found: " + "no ContextLoaderListener or DispatcherServlet registered?");                }                this.delegate = initDelegate(wac);            }            delegateToUse = this.delegate;        }    }    // Let the delegate perform the actual doFilter operation.    invokeDelegate(delegateToUse, request, response, filterChain);}

然后,需要的bean("springSessionRepositoryFilter") 是何时构造的?

看另外一部分配置,注解@EnableSpringHttpSession 或者xml声明(SpringHttpSessionConfiguration)。

a. SessionRepositoryFilter 由SpringHttpSessionConfiguration 构造,意味着我们启用spring-session。

b. httpSession的实现方式(Mongo、Jdbc、Redis...)基于此处SessionRepositoryFilter的构造入参,即sessionRepository

c. 配置spring容器中使用哪种SessionRepository,同样,通过两种方式: xml声明(RedisHttpSessionConfiguration) 或者 @EnableRedisHttpSession、@EnableJdbcHttpSession...

/** * web.xml 配置的httpsession bean 来自此处 * 构造spring-session filter 需要真正的存储对象 redis/jdbc/gemfire **/@Beanpublic  SessionRepositoryFilter springSessionRepositoryFilter(SessionRepository sessionRepository) {    SessionRepositoryFilter sessionRepositoryFilter = new SessionRepositoryFilter(sessionRepository);    sessionRepositoryFilter.setServletContext(this.servletContext);    sessionRepositoryFilter.setHttpSessionStrategy(this.httpSessionStrategy);    return sessionRepositoryFilter;}



备注:

1、java web获取spring bean 的方案可以直接配置DelegatingFilterProxy即可。灵活使用spring 的另外一种解决思路。

2、如上xml声明方式启用spring-session,只需要配置RedisHttpSessionConfiguration即可,该类继承自SpringHttpSessionConfiguration。

3、目前支持的分布式httpsession 包括:JdbcHttpSessionConfiguration ,RedisHttpSessionConfiguration , HazelcastHttpSessionConfiguration , GemFireHttpSessionConfiguration ,MongoHttpSessionConfiguration


原创粉丝点击