[Session共享]Spring-Redis实现Session共享

26 篇文章 0 订阅
4 篇文章 0 订阅

前言

实现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共享

下面我们启动两个项目测试下

1

2

至此已经实现了Tomcat集群间Session的共享

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值