SpringSession核心原理

一点点弄懂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();
		}
	}

使用的设计模式是装饰者模式!!

下图是我自己画的关系图,画的不好,请多见谅。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值