互联网垂直架构中session共享解决方案
1.session sticky方式
缺点:其中一台tomcat挂了,这tomcat上的session全部丢失,不符合高可用
2.session Relication方式
session复制的解决方式,这种方式实现简单,不需要更改代码,几台tomcat之间通过插件把session相互共享
缺点:增加了session在内网的传输开销,每台tomcat都需要保存所有机子session,内存占用严重
3.cookie base方式
把session直接存在用户的cookie中
缺点:每次传输需要带上seesion,增加了带宽的消耗,同时存在cookie不够安全
4.session集群存储redis
这是最常用的方式
优点:没有单点登录故障,扩展性强,实用于打的数据访问量
缺点:增加了网络消耗,需要中间件,维护成本
最佳方式的具体实现
1. 添加依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>
2. 配置mvc.xml
<bean id="redisHttpSessionConfiguration"
class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="600"/>
</bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="100" />
<property name="maxIdle" value="10" />
</bean>
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
<property name="hostName" value="${redis_hostname}"/>
<property name="port" value="${redis_port}"/>
<property name="password" value="${redis_pwd}" />
<property name="timeout" value="3000"/>
<property name="usePool" value="true"/>
<property name="poolConfig" ref="jedisPoolConfig"/>
</bean>
3. 配置web.xml
<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>
</filter-mapping>