- 问题描述
- 解决方案
- session复制
- session存储在客户端
- hash一致性算法
- 统一存储(中间件存储)
- 集成SpringSession
- 集成文档
- 核心原理
- 代码
由于现在服务都是分布式的,且域名存在多个。各个系统之前的信息可能需要保持一致(存在跨域名和跨服务甚至是多个同一服务的不同机器session一致性问题),通过原始session的存储方式必然产生信息缺失问题。
多个服务之间用session同步技术共享(例如 tomcat 可以共享session)
通过hash算法让用户访问指定的服务,避免了不一致的信息存取问题。
但跨域名访问仍旧存在问题,session作用域并没有改变,各个子域名间的session依旧不能共享
这种方式一般用的最多
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
start类加注解@EnableRedisHttpSession
@EnableRedisHttpSession
@EnableFeignClients
@SpringBootApplication
public class GulimallAuthServerApplication {
...
}



