前言
在开发中遇到一个关于用户体验的问题,每次当运维进行更新重启服务器时,都会导致会员平台中已登录的用户掉线。这是因为每个用户的会话信息及状态都是由session来保存的,而session对象是由服务器创建,并把session的Id以cookie的形式发送给客户端浏览器的(每个会话都有一个单独的sessionID)。当这个对象超过一定时间没有被使用或者服务器重启时,对象就会被销毁,也就导致了用户掉线。
解决办法
在解决问题过程中发现,只要记住了刚才用户的sessionID,重启服务器后仍使用原来的id,就不会掉线,也就是说要保证session不被改变才可以保持用户的登录状态。在这里使用了Spring Session Data Redis来实现session的共享(redis:高速缓存数据库),也就是说使用redis对session进行一个持久化操作(用mysql等数据库来单独存储session有点浪费了,速度也没有redis快),当服务器重启时,可以从redis中反序列化取出session,重新获取用户会话信息。
简要配置步骤:
(1)pom.xml加入依赖:spring-session-data-redis、spring-session,当然前提要有spring(4.3.5)、redis的依赖(redis使用了3.0版本)
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>1.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session</artifactId> <version>1.3.2.RELEASE</version> </dependency>
(2)applicationContext.xml配置文件中增加RedisHttpSessionConfiguration
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" > <property name="maxIdle" value="0" /> <property name="maxTotal" value="20" /> <property name="maxWaitMillis" value="1000" /> <property name="testOnBorrow" value="true" /> </bean> <!-- redis连接配置,依次为主机ip,端口,是否使用池,(usePool=true时)redis的池配置 --> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="0.0.0.0" p:port="1111" p:database="10" p:pool-config-ref="jedisPoolConfig"> </bean> <!-- 配置spring-session --> <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> <!-- 过期时间100分钟 --> <property name="maxInactiveIntervalInSeconds" value="6000"></property> </bean> </beans>
(3)web.xml中配置filter、session超时时间
<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> <session-config> <!--60*60*24--> <session-timeout>86400</session-timeout> </session-config>
配置完成后,基本就可以实现Session的共享了,重启服务器测试,已经登录的用户也不会发生掉线的情况了。