您的位置:首页 > 编程语言 > Java开发

Insight spring-session 配置(集成方式)

2017-07-26 21:40 295 查看
spring-session 项目实现了redis、jdbc、gemfire 版本的分布式httpsession。
集成方式分为注解、xml配置。
原理就是配置filter,代理原有的httpsession的生成、获取、销毁的实现
servlet、Spring集成方式-
org.springframework.web.context.support.WebApplicationContextUtils#getWebApplicationContext(javax.servlet.ServletContext)
Filter实现类 org.springframework.web.filter.DelegatingFilterProxySpring-Session实现类  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
**/
@Bean
public  SessionRepositoryFilter<? extends ExpiringSession> 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: