spring session redis实现会话共享

spring session redis实现会话共享

   点关注不迷路,欢迎再访!	

精简博客内容,尽量已行业术语来分享。
努力做到对每一位认可自己的读者负责。
帮助别人的同时更是丰富自己的良机。

一.前言介绍

spring session通过redis来实现多个服务器间的session共享的原理,其实就是将session独立出来不依赖原来的web容器,而是存放到与web容器没有耦合关系的redis容器中,这样即使是任何一台web容器挂了,也不会影响到其中的session,如下图所示:
在这里插入图片描述
spring session在spring框架中的实现原理,其实就是在请求request上通过DelegatingFilterProxy代理过滤器封装了一层,将原来存储在容器缓存的session变成存储在redis的session,所以在web.xml中的此filter必须得是在所有filter的前面。

二.引入依赖
 <dependency>
     <groupId>org.springframework.session</groupId>
     <artifactId>spring-session-data-redis</artifactId>
     <version>1.3.0.RELEASE</version>
</dependency>        
 <dependency>
     <groupId>org.springframework.session</groupId>
     <artifactId>spring-session</artifactId>
     <version>1.3.0.RELEASE</version>
</dependency>
三.实现代码

1.xml注入方式

<bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
		<property name="maxInactiveIntervalInSeconds" value="180"></property>
		<property name="configureRedisAction" value="NO_OP"></property>
</bean>

2.配置类方式

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3*60)
public class SessionConfig {

    //让Spring Session不再执行config命令
    @Bean
    public ConfigureRedisAction configureRedisAction(){
        return ConfigureRedisAction.NO_OP;
    }
}

注意,用了spring session后,在web.xml设置的session过期时间是无效。因为此session已经不是原来的存储在容器缓存内的session了,而是被封装多了一层后存储在redis的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是否一致
在这里插入图片描述
redis客户端上查看session
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值