• Spring Session实现分布式session的简单示例



         前面有用 tomcat-redis-session-manager来实现分布式session管理,但是它有一定的局限性,主要是跟tomcat绑定太紧了,这里改成用Spring Session来管理分布式session,Spring Session就完全实现了与具体的容器无关,如果需要了解如何用tomcat-redis-session-manager实现分分布式session,请看我之前的文章,下面正式进入主题,Spring Session项目搭建。

    1. 引入Spring Session maven依赖

            <!-- spring session begin -->
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.9.0</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-redis</artifactId>
                <version>1.5.2.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.session</groupId>
                <artifactId>spring-session</artifactId>
                <version>1.3.1.RELEASE</version>
            </dependency>
            <!-- spring session end -->            

    2. Spring配置文件中添加Spring Session相关配置(这里重点体现Spring Session,因此并没有列出redis相关配置,需要可参考实例代码)

        <!-- Spring Session begin -->
        <bean id="redisHttpSessionConfiguration"
            class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
            <property name="maxInactiveIntervalInSeconds" value="1800" />
        </bean>
        <!-- Spring Session end -->

    3. 在web.xml中配置Spring Session的Filter,它必须放在所有Filter的前面

        <!-- 添加一个session代理filter,来包装Servlet的getSession,需要放在所有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>

    这几乎就是所有的步骤了,是不是感觉很简单呢?赶快自己动手试一试吧,看起来高大上的分布式Session就这样被Spring Session搞定了!

    下面是我的github源码地址:

    https://github.com/13babybear/bounter-springsession

    欢迎提供你宝贵的意见!

  • 相关阅读:
    Asp.NetCore Web开发之初始文件解析
    Asp.NetCore Web开发之创建项目
    Asp.NetCore Web开发之ADO.Net
    C#中的元组(Tuple)和结构体(struct)
    C#中的扩展方法
    HTTP方法:GET和POST
    Chapter 3准备:基础设施与TA框架
    Chapter 2 全程测试:闪光的思想
    SOAP协议
    接口自动化测试——入门
  • 原文地址:https://www.cnblogs.com/gdufs/p/6833270.html
Copyright © 2020-2023  润新知