一点点弄懂SpringSession核心原理!看了就懂!
使用的JDK版本为JDK11,同时使用Redis存储Session,还有通过内存等存储的,原理都一样!先把图放在这!
SpringSession使用是通过在启动类上加一个注解!@EnableRedisHttpSession
点进注解!发现导入了配置类RedisHttpSessionConfiguration。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(RedisHttpSessionConfiguration.class)
@Configuration(proxyBeanMethods = false)
public @interface EnableRedisHttpSession {
}
点进RedisHttpSessionConfiguration这个类,可以看到,这个类继承了SpringHttpSessionConfiguration。
RedisHttpSessionConfiguration向容器中放入了一个RedisIndexedSessionRepository,这个类实现了SessionRepository,RedisIndexedSessionRepository的作用就是对Session进行增删改的作用!
SpringHttpSessionConfiguration向容器中放入了一个SessionRepositoryFilter,这是个过滤器!看源码,这个过滤器传入的参数就是容器中的SessionRepository,也就是RedisIndexedSessionRepository!
@Configuration(proxyBeanMethods = false)
public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguration{
@Bean
public RedisIndexedSessionRepository sessionRepository() {
}
}
@Configuration(proxyBeanMethods = false)
public class SpringHttpSessionConfiguration implements ApplicationContextAware {
@Bean
public <S extends Session> SessionRepositoryFilter<? extends Session> springSessionRepositoryFilter(
SessionRepository<S> sessionRepository) {
SessionRepositoryFilter<S> sessionRepositoryFilter = new SessionRepositoryFilter<>(sessionRepository);
sessionRepositoryFilter.setHttpSessionIdResolver(this.httpSessionIdResolver);
return sessionRepositoryFilter;
}
}
点进SessionRepositoryFilter中,SpringSession的核心原理就是下面的代码,通过过滤器,将原来的请求进行包装,SessionRepositoryRequestWrapper是SessionRepositoryFilter的内部类,其使用的也就是传给SessionRepositoryFilter的RedisIndexedSessionRepository。
这样这个被包装的请求使用的就是RedisIndexedSessionRepository对Session进行修改、删除、获取!
这个请求被放行到Controller,那么Controller中获取到的实际是使用RedisIndexedSessionRepository进行修改的自定义的Session!
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
request.setAttribute(SESSION_REPOSITORY_ATTR, this.sessionRepository);
SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(request, response);
SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(wrappedRequest,
response);
try {
filterChain.doFilter(wrappedRequest, wrappedResponse);
}
finally {
wrappedRequest.commitSession();
}
}
使用的设计模式是装饰者模式!!
下图是我自己画的关系图,画的不好,请多见谅。