SpringBoot 整合 SpringSession

https://docs.spring.io/spring-session/docs/2.5.0/reference/html5/#samples
auth 服务、product 服务、 search 服务 pom文件

  1. <!-- 整合 spring session 实现 session 共享-->
  2. <dependency>
  3. <groupId>org.springframework.session</groupId>
  4. <artifactId>spring-session-data-redis</artifactId>
  5. </dependency>

配置文件 application.yaml

  1. spring:
  2. session:
  3. store-type: redis

主启动类增加注解:@EnableRedisHttpSession

配置类:

  1. @Configuration
  2. public class GulimallSessionConfig {
  3. @Bean
  4. public CookieSerializer cookieSerializer() {
  5. DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
  6. //放大作用域
  7. cookieSerializer.setDomainName("gulimall.com");
  8. cookieSerializer.setCookieName("GULISESSION");
  9. return cookieSerializer;
  10. }
  11. @Bean
  12. public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
  13. return new GenericJackson2JsonRedisSerializer();
  14. }
  15. }

SpringSession 核心原理

@EnableRedisHttpSession 导入 RedisHttpSessionConfiguration 配置
1、给容器中添加了一个组件 RedisOperationsSessionRepository:Redis操作session,session的增删改查封装类;
2、继承 SpringHttpSessionConfiguration 初始化了一个 SessionRepositoryFilter:session 存储过滤器;每个请求过来都必须经过 Filter 组件;创建的时候,自动从容器中获取到了 SessionRepository;
SessionRepositoryFilter:

  • 将原生的 HttpServletRequest Response 包装成 SessionRepositoryRequestWrapper ResponseWrapper;包装后的对象应用到了后面整个执行链;
  • 以后获取 request.getSession(); 都会调用 wrappedRequesr.getSession(); 从SessionRepository获取;

3、装饰者模式

  1. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
  2. request.setAttribute(SESSION_REPOSITORY_ATTR, this.sessionRepository);
  3. SessionRepositoryFilter<S>.SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryFilter.SessionRepositoryRequestWrapper(request, response);
  4. SessionRepositoryFilter.SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryFilter.SessionRepositoryResponseWrapper(wrappedRequest, response);
  5. try {
  6. filterChain.doFilter(wrappedRequest, wrappedResponse);
  7. } finally {
  8. wrappedRequest.commitSession();
  9. }
  10. }