前言
实现Session共享的方法有很多种,利用redis、mysql或Tomcat等均可实现Session共享,本次是使用Redis实现Session共享。以后会继续更新文章,推出其他解决方案。
环境准备
1、两个Tomcat
2、两个项目
首先我们简单配置一下项目,在index.jsp中添加如下测试代码,用来测试服务器间的的Session是否同步。
<body>
SessionID:<%=session.getId()%>
<BR>
SessionIP:<%=request.getServerName()%>
<BR>
SessionPort:<%=request.getServerPort()%>
</body>
下面我们开始使用Redis实现Session共享
Jar包准备:
- commons-pool2-2.4.2.jar(可以与commons-pool-1.X.jar并存)
- jedis-2.9.0.jar
- spring-data-redis-1.7.3.RELEASE.jar
- spring-session-1.2.2.RELEASE.jar
- spring(本次使用的为4.2.5版本)
配置redis的properties
# Redis settings
redis.host=127.0.0.1
redis.port=6379
redis.pass=
redis.maxIdle=300
redis.testOnBorrow=true
redis.maxTotal=100
#redis.maxActive=600
#redis.maxWait=1000
Spring整合Redis
<bean id="redisHttpSessionConfiguration"
class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="600" />
</bean>
<!--
由于之前使用的是低版本的redis Jar包,本次更换为高版本的redis Jar
所有没有maxActive和maxWait属性了,不注释掉的话会启动报错
-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<!-- <property name="maxActive" value="${redis.maxActive}" /> -->
<property name="maxTotal" value="${redis.maxTotal}" />
<!-- <property name="maxWait" value="${redis.maxWait}" /> -->
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
web.xml增加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>
</filter-mapping>
至此Spring-redis已经实现了session共享
下面我们启动两个项目测试下
至此已经实现了Tomcat集群间Session的共享