Day424.SpringSession&SSO单点登录 -谷粒商城

SpringSession

通过SpringSession来解决分布式之间服务Session共享问题

一、SpringBoot 整合 SpringSession

https://docs.spring.io/spring-session/docs/2.5.0/reference/html5/#samples

  • 引入依赖
	
<dependency>
    <groupId>org.springframework.sessiongroupId>
    <artifactId>spring-session-data-redisartifactId>
dependency>
  • application.yaml
spring:
  session:
    store-type: redis
  • 开启功能

主启动类增加注解:@EnableRedisHttpSession

  • redis配置
spring.redis.host=localhost # Redis server host.
spring.redis.password= # Login password of the redis server.
spring.redis.port=6379 # Redis server port.
  • com.achang.achangmall.auth.conf.AchangmallSessionConfig
@Configuration
public class AchangmallSessionConfig {
     
    @Bean
    public CookieSerializer cookieSerializer() {
     
        DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
        //放大作用域
        cookieSerializer.setDomainName("achangmall.com");
        cookieSerializer.setCookieName("ACHANGSESSION");
        return cookieSerializer;
    }

    @Bean
    public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
     //使用json存储redis,而不是默认的序列化存储
        return new GenericJackson2JsonRedisSerializer();
    }

}

二、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、装饰者模式

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
     
    request.setAttribute(SESSION_REPOSITORY_ATTR, this.sessionRepository);
    SessionRepositoryFilter<S>.SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryFilter.SessionRepositoryRequestWrapper(request, response);
    SessionRepositoryFilter.SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryFilter.SessionRepositoryResponseWrapper(wrappedRequest, response);

    try {
     
        filterChain.doFilter(wrappedRequest, wrappedResponse);
    } finally {
     
        wrappedRequest.commitSession();
    }

}

SSO-单点登录

Single Sign On 一处登陆、处处可用

参考:https://gitee.com/xuxueli0323/xxl-sso

Day424.SpringSession&SSO单点登录 -谷粒商城_第1张图片

Day424.SpringSession&SSO单点登录 -谷粒商城_第2张图片

你可能感兴趣的:(谷粒商城,springsession,session,sso,单点登录,springboot)