分布式session中一般会通过,Ngnix、application server、session持久化(此处讲Redis)共同发挥作用。
1.粘性Session
通过ip_hash, 每次访问只访问当前服务器。
2.服务器Session复制
配置tomat的配置文档中的distributable节点。
3.Session服务器
通过Spring Session配置,对应的redis模式。
3.1 一种是tomcatdesession-manager的拓展
3.2 一种是spring session通过httpsession的支持. 具体思路是通过filter去拦截:
具体看如下的分析:
session基于redis共享有两种基本的方案
1、基于容器自身的扩展,比如tomcat的session-manage,可以参考如下
地址进行配置https://github.com/jcoleman/tomcat-redis-session-manager
这个方案只适用tomcat容器,而且容器需要配置,这里不具体展开,有需要的可以参考上面的地址进行配置。但是这个方案有一个好处,可以适用于struts2和springmvc的场景,而且对springmvc没有版本要求。
2、基于spring-session的方案,spring-session的好处不仅仅是session共享,它还可以应用于多终端session共享,websocket,restful api等场景。下面具体说明一下
配置。特别说明spring-session是基于springmvc4.0以后的版本的,所以版本不匹配的就不能使用。
mave配置
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.2.2.RELEASE</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.9.RELEASE</version>
</dependency>
xml配置
spring.xml
<bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration" >
<property name="maxInactiveIntervalInSeconds" value="1800" />
</bean>
<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="192.168.17.24" />
<property name="port" value="6379" />
</bean>
web.xml
<!-- 分布式Session共享Filter -->
<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</f