分布式Session一致性?
说白了就是服务器集群Session共享的问题
Session的作用?
Session 是客户端与服务器通讯会话跟踪技术,服务器与客户端保持整个通讯的会话基本信息。
客户端在第一次访问服务端的时候,服务端会响应一个sessionId并且将它存入到本地cookie中,在之后的访问会将cookie中的sessionId放入到请求头中去访问服务器,如果通过这个sessionid没有找到对应的数据那么服务器会创建一个新的sessionid并且响应给客户端。
分布式Session存在的问题?
假设第一次访问服务A生成一个sessionid并且存入cookie中,第二次却访问服务B客户端会在cookie中读取sessionid加入到请求头中,如果在服务B通过sessionid没有找到对应的数据那么它创建一个新的并且将sessionid返回给客户端,这样并不能共享我们的Session无法达到我们想要的目的。
解决方案:
- 使用cookie来完成(很明显这种不安全的操作并不可靠)
- 使用Nginx中的ip绑定策略,同一个ip只能在指定的同一个机器访问(不支持负载均衡)
- 利用数据库同步session(效率不高)
- 使用tomcat内置的session同步(同步可能会产生延迟)
- 使用token代替session
- 我们使用spring-session以及集成好的解决方案,存放在redis中
目前项目中存在的问题
启动两个项目端口号分别为8080,8081。
依赖:
<!--springboot父项目-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!--web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
创建测试类:
/**
* Author: zhangsan
* date: 2018/12/14
*/
@RestController
public class TestSessionController {
@Value("${server.port}")
private Integer projectPort;// 项目端口
@RequestMapping("/createSession")
public String createSession(HttpSession session, String name) {
session.setAttribute("name", name);
return "当前项目端口:" + projectPort + " 当前sessionId :" + session.getId() + "在Session中存入成功!";
}
@RequestMapping("/getSession")
public String getSession(HttpSession session) {
return "当前项目端口:" + projectPort + " 当前sessionId :" + session.getId() + " 获取的姓名:" + session.getAttribute("name");
}
}
application.yml配置:
server:
port: 8080
修改电脑的hosts文件,文件地址是C:\WINDOWS\system32\drivers\etc,修改如下所示:
#将本机ip映射到www.hello.com上
127.0.0.1 www.hello.com
在这里我们开启nginx集群,修改配置:
#加入
#默认使用轮询,
upstream backserver{
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
#修改server中的local
location / {
proxy_pass http://backserver;
index index.html index.htm;
}
我们直接通过轮询机制来访问首先向Session中存入一个姓名,http://www.hello.com/createSession?name=zhangsan
当前项目端口:8081 当前sessionId :0F20F73170AE6780B1EC06D9B06210DB在Session中存入成功!
因为我们使用的是默认的轮询机制那么下次肯定访问的是8080端口,我们直接获取以下刚才存入的值http://www.hello.com/getSession
当前项目端口:8080 当前sessionId :C6663EA93572FB8DAE27736A553EAB89 获取的姓名:null
这个时候发现8080端口中并没有我们存入的值,并且sessionId也是与8081端口中的不同。
别急继续访问,因为轮询机制这个时候我们是8081端口的服务器,那么之前我们是在8081中存入了一个姓名。那么我们现在来访问以下看看是否能够获取到我们存入的姓名:zhangsan,继续访问:http://www.hello.com/getSession
当前项目端口:8081 当前sessionId :005EE6198C30D7CD32FBD8B073531347 获取的姓名:null
8080端口我们没有存入,连8081端口存入的都没有呢?
我们仔细观察一下第三次访问8081的端口sessionid都不一样了,是因为我们在第二次去访问的时候访问的是8080端口这个时候客户端在cookie中获取8081的端口去8080服务器上去找,没有找到后重新创建了一个session并且将sessionid响应给客户端,客户端又保持到cookid中替换了之前8081的sessionid,那么第三次访问的时候拿着第二次访问的sessionid去找又找不到然后又创建。一直反复循环。
如何解决这两个服务之间的共享问题呢?
spring已经给我们想好了问题并且已经提供出解决方案:spring-session 不了解的可以去百度了解下。
我们首先打开redis并且在pom.xml中添加依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--spring session 与redis应用基本环境配置,需要开启redis后才可以使用,不然启动Spring boot会报错 -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
修改yml配置文件:
server:
port: 8081
spring:
redis:
database: 0
host: localhost
port: 6379
jedis:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
timeout: 10000
redis:
hostname: localhost
port: 6379
#password: 123456
添加Session配置类
/**
* Author: zhangsan
* date: 2018/12/14
*/
//这个类用配置redis服务器的连接
//maxInactiveIntervalInSeconds为SpringSession的过期时间(单位:秒)
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
public class SessionConfig {
// 冒号后的值为没有配置文件时,制动装载的默认值
@Value("${redis.hostname:localhost}")
private String hostName;
@Value("${redis.port:6379}")
private int port;
// @Value("${redis.password}")
// private String password;
@Bean
public JedisConnectionFactory connectionFactory() {
JedisConnectionFactory connection = new JedisConnectionFactory();
connection.setPort(port);
connection.setHostName(hostName);
//connection.setPassword(password);
// connection.setDatabase(0);
return connection;
}
}
maxInactiveIntervalInSeconds
: 设置 Session 失效时间,使用 Redis Session 之后,原 Spring Boot 的 server.session.timeout 属性不再生效。
经过上面的配置后,Session 调用就会自动去Redis存取。另外,想要达到 Session 共享的目的,只需要在其他的系统上做同样的配置即可。
初始化Session配置:
/**
* Author: zhangsan
* date: 2018/12/14
*/
//初始化Session配置
public class SessionInitializer extends AbstractHttpSessionApplicationInitializer {
public SessionInitializer() {
super(SessionConfig.class);
}
}
然后我们继续启动8080,8081来进行测试:
首先存入一个姓名http://www.hello.com/createSession?name=zhangsan
当前项目端口:8080 当前sessionId :cf5c029a-2f90-4b7e-8345-bf61e0279254在Session中存入成功!
应该轮询机制那么下次一定是8081,竟然已经解决session共享问题了那么肯定能够获取到了,竟然这样那么我们直接来获取下姓名http://www.hello.com/getSession:
当前项目端口:8081 当前sessionId :cf5c029a-2f90-4b7e-8345-bf61e0279254 获取的姓名:zhangsan
这个时候我们发现不仅能够获取到值而且连sessionid都一致了。
实现原理:
就是当Web服务器接收到http请求后,当请求进入对应的Filter进行过滤,将原本需要由web服务器创建会话的过程转交给Spring-Session进行创建,本来创建的会话保存在Web服务器内存中,通过Spring-Session创建的会话信息可以保存第三方的服务中,如:redis,mysql等。Web服务器之间通过连接第三方服务来共享数据,实现Session共享!
Spring Session Redis 的原理简析
看了上面的配置,我们知道开启 Redis Session 的“秘密”在 @EnableRedisHttpSession 这个注解上。打开 @EnableRedisHttpSession 的源码:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(RedisHttpSessionConfiguration.class)
@Configuration
public @interface EnableRedisHttpSession {
//Session默认过期时间,秒为单位,默认30分钟
int maxInactiveIntervalInSeconds() default MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS;
//配置key的namespace,默认的是spring:session,如果不同的应用共用一个redis,应该为应用配置不同的namespace,这样才能区分这个Session是来自哪个应用的
String redisNamespace() default RedisOperationsSessionRepository.DEFAULT_NAMESPACE;
//配置刷新Redis中Session的方式,默认是ON_SAVE模式,只有当Response提交后才会将Session提交到Redis
//这个模式也可以配置成IMMEDIATE模式,这样的话所有对Session的更改会立即更新到Redis
RedisFlushMode redisFlushMode() default RedisFlushMode.ON_SAVE;
//清理过期Session的定时任务默认一分钟一次。
String cleanupCron() default RedisHttpSessionConfiguration.DEFAULT_CLEANUP_CRON;
}
这个注解的主要作用是注册一个 SessionRepositoryFilter,这个 Filter 会拦截所有的请求,对 Session 进行操作,具体的操作细节会在后面讲解,这边主要了解这个注解的作用是注册 SessionRepositoryFilter 就行了。注入 SessionRepositoryFilter 的代码在 RedisHttpSessionConfiguration 这个类中。
@Configuration
@EnableScheduling
public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguration
implements BeanClassLoaderAware, EmbeddedValueResolverAware, ImportAware,
SchedulingConfigurer {
...
}
RedisHttpSessionConfiguration 继承了 SpringHttpSessionConfiguration,SpringHttpSessionConfiguration 中注册了 SessionRepositoryFilter。见下面代码。
@Configuration
public class SpringHttpSessionConfiguration implements ApplicationContextAware {
...
@Bean
public <S extends Session> SessionRepositoryFilter<? extends Session> springSessionRepositoryFilter(
SessionRepository<S> sessionRepository) {
SessionRepositoryFilter<S> sessionRepositoryFilter = new SessionRepositoryFilter<>(sessionRepository);
sessionRepositoryFilter.setServletContext(this.servletContext);
sessionRepositoryFilter.setHttpSessionIdResolver(this.httpSessionIdResolver);
return sessionRepositoryFilter;
}
...
}
我们发现注册 SessionRepositoryFilter 时需要一个 SessionRepository 参数,这个参数是在 RedisHttpSessionConfiguration 中被注入进入的。
@Configuration
@EnableScheduling
public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguration
implements BeanClassLoaderAware, EmbeddedValueResolverAware, ImportAware,SchedulingConfigurer {
@Bean
public RedisOperationsSessionRepository sessionRepository() {
RedisTemplate<Object, Object> redisTemplate = createRedisTemplate();
RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository(redisTemplate);
sessionRepository.setApplicationEventPublisher(this.applicationEventPublisher);
if (this.defaultRedisSerializer != null) {
sessionRepository.setDefaultSerializer(this.defaultRedisSerializer);
}
sessionRepository.setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds);
if (StringUtils.hasText(this.redisNamespace)) {
sessionRepository.setRedisKeyNamespace(this.redisNamespace);
}
sessionRepository.setRedisFlushMode(this.redisFlushMode);
int database = resolveDatabase();
sessionRepository.setDatabase(database);
return sessionRepository;
}
}
上面主要讲的就是 Spring-Session 会自动注册一个 SessionRepositoryFilter ,这个过滤器会拦截所有的请求。下面就具体看下这个过滤器对拦截下来的请求做了哪些操作。
SessionRepositoryFilter 拦截到请求后,会先将 request 和 response 对象转换成 Spring 内部的包装类 SessionRepositoryRequestWrapper 和 SessionRepositoryResponseWrapper 对象。SessionRepositoryRequestWrapper 类重写了原生的getSession
方法。代码如下:
@Override
public HttpSessionWrapper getSession(boolean create) {
//通过request的getAttribue方法查找CURRENT_SESSION属性,有直接返回
HttpSessionWrapper currentSession = getCurrentSession();
if (currentSession != null) {
return currentSession;
}
//查找客户端中一个叫SESSION的cookie,通过sessionRepository对象根据SESSIONID去Redis中查找Session
S requestedSession = getRequestedSession();
if (requestedSession != null) {
if (getAttribute(INVALID_SESSION_ID_ATTR) == null) {
requestedSession.setLastAccessedTime(Instant.now());
this.requestedSessionIdValid = true;
currentSession = new HttpSessionWrapper(requestedSession, getServletContext());
currentSession.setNew(false);
//将Session设置到request属性中
setCurrentSession(currentSession);
//返回Session
return currentSession;
}
}
else {
// This is an invalid session id. No need to ask again if
// request.getSession is invoked for the duration of this request
if (SESSION_LOGGER.isDebugEnabled()) {
SESSION_LOGGER.debug(
"No session found by id: Caching result for getSession(false) for this HttpServletRequest.");
}
setAttribute(INVALID_SESSION_ID_ATTR, "true");
}
//不创建Session就直接返回null
if (!create) {
return null;
}
if (SESSION_LOGGER.isDebugEnabled()) {
SESSION_LOGGER.debug(
"A new session was created. To help you troubleshoot where the session was created we provided a StackTrace (this is not an error). You can prevent this from appearing by disabling DEBUG logging for "
+ SESSION_LOGGER_NAME,
new RuntimeException(
"For debugging purposes only (not an error)"));
}
//通过sessionRepository创建RedisSession这个对象,可以看下这个类的源代码,如果
//@EnableRedisHttpSession这个注解中的redisFlushMode模式配置为IMMEDIATE模式,会立即
//将创建的RedisSession同步到Redis中去。默认是不会立即同步的。
S session = SessionRepositoryFilter.this.sessionRepository.createSession();
session.setLastAccessedTime(Instant.now());
currentSession = new HttpSessionWrapper(session, getServletContext());
setCurrentSession(currentSession);
return currentSession;
}
当调用 SessionRepositoryRequestWrapper 对象的getSession
方法拿 Session 的时候,会先从当前请求的属性中查找CURRENT_SESSION
属性,如果能拿到直接返回,这样操作能减少Redis操作,提升性能。
到现在为止我们发现如果redisFlushMode
配置为 ON_SAVE 模式的话,Session 信息还没被保存到 Redis 中,那么这个同步操作到底是在哪里执行的呢?
仔细看代码,我们发现 SessionRepositoryFilter 的doFilterInternal
方法最后有一个 finally 代码块,这个代码块的功能就是将 Session同步到 Redis。
@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, this.servletContext);
SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(
wrappedRequest, response);
try {
filterChain.doFilter(wrappedRequest, wrappedResponse);
}
finally {
//将Session同步到Redis,同时这个方法还会将当前的SESSIONID写到cookie中去,同时还会发布一
//SESSION创建事件到队列里面去
wrappedRequest.commitSession();
}
}
简单总结#
主要的核心类有:
- @EnableRedisHttpSession:开启 Session 共享功能;
- RedisHttpSessionConfiguration:配置类,一般不需要我们自己配置,主要功能是配置 SessionRepositoryFilter 和 RedisOperationsSessionRepository 这两个Bean;
- SessionRepositoryFilter:拦截器,Spring-Session 框架的核心;
- RedisOperationsSessionRepository:可以认为是一个 Redis 操作的客户端,有在 Redis 中进行增删改查 Session 的功能;
- SessionRepositoryRequestWrapper:Request 的包装类,主要是重写了
getSession
方法 - SessionRepositoryResponseWrapper:Response的包装类。
原理简要总结:
当请求进来的时候,SessionRepositoryFilter 会先拦截到请求,将 request 和 response 对象转换成 SessionRepositoryRequestWrapper 和 SessionRepositoryResponseWrapper 。后续当第一次调用 request 的getSession方法时,会调用到 SessionRepositoryRequestWrapper 的getSession
方法。这个方法是被从写过的,逻辑是先从 request 的属性中查找,如果找不到;再查找一个key值是"SESSION"的 Cookie,通过这个 Cookie 拿到 SessionId 去 Redis 中查找,如果查不到,就直接创建一个RedisSession 对象,同步到 Redis 中。
说的简单点就是:拦截请求,将之前在服务器内存中进行 Session 创建销毁的动作,改成在 Redis 中创建。