spring mvc

spring-session-data-redis共享方案

2018-07-19  本文已影响112人  spacedong

传统的解决方案

在传统的 HTTP session 解决方案中,session 是存储在 JVM 的堆内存中。这个 JVM 和运行代码的 JVM 是一样的。

现在的解决方案

为了解决在传统的 HTTP session 管理方案中的问题,需要把 session 存储在独立的数据结构中,如:Redis、Memcache等缓存中,让 session 实现共享。

实践

准备 Spring - session

1、第一步:添加依赖包

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
    <version>2.0.4.RELEASE</version>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

2、第二步: web.xml 文件中添加 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>  

3、第三步:编写 spring-redis 的配置文件,根据自己的配置来具体设置。

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" />

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

    <bean id="jedisConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        destroy-method="destroy">
        //redis的主机名
        <property name="hostName" value="${redis.host}" />
        //redis的连接端口
        <property name="port" value="${redis.port}" />
        //连接超时时间
        <property name="timeout" value="${redis.timeout}" />
        <property name="usePool" value="true" />
        <property name="poolConfig" ref="jedisPoolConfig" />
        //这里是redis中的数据库的设置,默认是存在第一个库中
        <property name="database" value="0"/>
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
    </bean>

4、第四步:在 Spring.xml 的配置文件中设置

<!-- Redis的配置-->
<import resource="classpath:spring-redis.xml"/>
现在就可以完成关于spring-session的共享了,后续可能还涉及到Nginx的负载均衡等,请期待下篇文章。
上一篇 下一篇

猜你喜欢

热点阅读