分布式、多节点部署是当保证项目稳定运行的一个选择,那么问题来了,集群部署时一般会用到负载均衡,这就涉及到了session共享问题。用户的每次请求可能访问的服务器都不一样,服务器间共享session,用户只需登录一次即可,对用户来说好像就是一台服务器。
解决方案有不少,springSession结合redis是一种最佳的选择之一。这种方案不依赖与web服务器的版本,任何版本的web服务器均可支持。不多说,给出简要配置。
官方给出了java和xml两种配置,这里只给出xml配置。
1、maven依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
2、 src/main/webapp/WEB-INF/spring/spring-session.xml
<?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-4.0.xsd">
<!-- 将HttpSession转化为Spring Session,将Session实例存放在Redis中 -->
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="3600"></property><!--session过期时间,默认1800秒-->
</bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"
p:minIdle="50"
p:maxIdle="1000"
p:maxTotal="1000"
p:maxWaitMillis="2000"
p:testOnBorrow="false"
p:testOnReturn="false"
p:testWhileIdle="true"
p:blockWhenExhausted="true"/>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="jedisPoolConfig"/>
<property name="hostName" value="101.81.51.150" />
<property name="port" value="6379" />
<property name="password" value="xxxabc" />
<property name="timeout" value="2000" />
<property name="usePool" value="true" />
<!-- <constructor-arg name="poolConfig" ref="jedisPoolConfig" /> -->
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
</bean>
</beans>
3、src/main/webapp/WEB-INF/web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/*.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<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>
</filter-mapping>
参考https://docs.spring.io/spring-session/docs/1.3.3.RELEASE/reference/html5/