栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

谷粒商城高级篇——session一致性解决方案(SpringSession)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

谷粒商城高级篇——session一致性解决方案(SpringSession)

session一致性解决方案
  • 问题描述
  • 解决方案
    • session复制
    • session存储在客户端
    • hash一致性算法
    • 统一存储(中间件存储)
  • 集成SpringSession
    • 集成文档
    • 核心原理
    • 代码

问题描述

由于现在服务都是分布式的,且域名存在多个。各个系统之前的信息可能需要保持一致(存在跨域名和跨服务甚至是多个同一服务的不同机器session一致性问题),通过原始session的存储方式必然产生信息缺失问题。

解决方案 session复制

多个服务之间用session同步技术共享(例如 tomcat 可以共享session)

session存储在客户端

hash一致性算法

通过hash算法让用户访问指定的服务,避免了不一致的信息存取问题。
但跨域名访问仍旧存在问题,session作用域并没有改变,各个子域名间的session依旧不能共享

统一存储(中间件存储)

这种方式一般用的最多

集成SpringSession 集成文档

springsession官方文档

核心原理

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.SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryFilter.SessionRepositoryRequestWrapper(request, response);
    SessionRepositoryFilter.SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryFilter.SessionRepositoryResponseWrapper(wrappedRequest, response);

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

}
代码

auth 服务、product 服务、 search 服务 pom文件


  org.springframework.session
  spring-session-data-redis

配置文件 application.yaml

spring:
  session:
    store-type: redis

主启动类增加注解:@EnableRedisHttpSession

@Configuration
public class GulimallSessionConfig {
    @Bean
    public cookieSerializer cookieSerializer() {
        DefaultcookieSerializer cookieSerializer = new DefaultcookieSerializer();
        //放大作用域
        cookieSerializer.setDomainName("gulimall.com");
        cookieSerializer.setcookieName("GULISESSION");
        return cookieSerializer;
    }

    @Bean
    public RedisSerializer springSessionDefaultRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
}
 

start类加注解@EnableRedisHttpSession

@EnableRedisHttpSession
@EnableFeignClients
@SpringBootApplication
public class GulimallAuthServerApplication {
...
}
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号