spring session+redis解决负载均衡下的session共享问题

java web项目,不依赖于web容器,实现负载均衡,必须解决session共享问题。
spring-session +redis是最方面快捷的,不用重复造轮子,且不用修改项目的代码,并且使项目使用的session与web容器解耦,
完全由容器的httpsession转为使用spring提供的session.
具体怎么使用,请访问spring的官方网站
项目中使用spring session+redis的步骤。
项目使用的是maven结构的web项目

  1. pom.xm
<!-- spring-session begin-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
            <version>1.3.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.1</version>
        </dependency>
        <!-- spring-session end-->

注意:刚开始我的spring框架包(就是好多spring的包)用的是4.0的,但是启动tomcat服务器的时候报错,说不能初始化redisTemplate,跑去stackofflow上看,有说是因为jar的问题,需要升级spring框架必须高于4.2.1,因为redistemplate换了构造器。于是将spring框架升到4.3.7.RELEASE。就ok了。
2.配置filter
在web.xml中,加上这段配置 必须位于filter链的最前面

<!-- spring-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>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>

3.在applicationContext.xml(这是我的spring容器配置文件的名字)中注册需要的bean。(用注解也行,但我是用的xml配置)

 <!-- redis -->
       <bean id="jedisPoolConfig"  class="redis.clients.jedis.JedisPoolConfig">
       </bean>
       
       <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
            <property name="hostName" value="localhost" />
            <property name="port" value="6379" />
            <property name="password" value="****"/>
            <property name="usePool" value="true"/>
            <property name="poolConfig" ref="jedisPoolConfig"/>
       </bean>
       
       <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="jedisConnectionFactory"/>
       </bean>
       
       <!-- 将session放入redis -->
       <bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
            <property name="maxInactiveIntervalInSeconds" value="1800"/>
       </bean>

系统中的代码一点也不用改动真的解耦啊,spring非常强大!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值