`

redis 集群中Session解决方案之Spring Session

 
阅读更多
集群中Session解决方案之Spring Session http://dreamer-yzy.github.io/2015/01/14/%E9%9B%86%E7%BE%A4%E4%B8%ADSession%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88%E4%B9%8BSpring-Session/

Shiro通过Redis管理会话实现集群 http://sgq0085.iteye.com/blog/2170405


Maven
<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session-data-redis</artifactId>
  <version>1.0.0.BUILD-SNAPSHOT</version>
  <type>pom<type>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>4.1.3.RELEASE</version>
</dependency>

Hello World(以Spring为基础,其他框架,也可以参考该思路作小修改即可)



web.xml 添加以下 Filter
<filter>
    <filter-name>spring-session</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetBeanName</param-name>
        <param-value>springSession</param-value>
    </init-param>
</filter>
 
<filter-mapping>
    <filter-name>spring-session</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>




spring.xml 添加
<!--这里添加的是Redis,因为使用的是Spring里自带的Redis的Session策略 -->
<bean id="v2redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
    p:host-name="10.0.0.40" p:port="6379" p:use-pool="true" p:database="8" />
 
<bean id="stringRedisSerializer"
    class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
 
<bean id="v2redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
    p:connection-factory-ref="v2redisConnectionFactory"
    p:keySerializer-ref="stringRedisSerializer"
    p:valueSerializer-ref="stringRedisSerializer"
    p:hashKeySerializer-ref="stringRedisSerializer"
    p:hashValueSerializer-ref="stringRedisSerializer" />
<!-- 这里的是为了下面的 Session策略过滤器提供构造函数传入的参数,因为Session过滤器要依赖该对象来构造,所以创建一个先 -->
<bean name="redisOperationsSessionRepository" class="org.springframework.session.data.redis.RedisOperationsSessionRepository">
    <constructor-arg ref="v2redisConnectionFactory"></constructor-arg>
</bean>
 
<!-- 这个是Session策略过滤器,即将容器原有的Session持久化机制,代替为Spring的 Redis持久化Session机制。 -->
<!-- 注意,这个名字与 web.xml里的targetBean的下value是要一致的。 -->
<bean name="springSession" class="org.springframework.session.web.http.SessionRepositoryFilter">
    <constructor-arg ref="redisOperationsSessionRepository"></constructor-arg>
</bean>

使用上跟普通使用 Session 的方式是一样的。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics