1. 程式人生 > >用Redis管理Session

用Redis管理Session

對象 -s interval maven define eth pattern property pen

maven

    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.8.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.session</groupId>
      <artifactId>spring-session-data-redis</artifactId>
      <version>1.3.1.RELEASE</version>
      <type>pom</type>
    </dependency>

web.xml

  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>

Spirng配置文件

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

    <bean id="jedisPoolConfig" class
="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="100" /> <property name="maxIdle" value="10" /> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="hostName" value="localhost"/> <property name="port" value="6379"/> <property name="timeout" value="3000"/> <property name="usePool" value="true"/> <property name="poolConfig" ref="jedisPoolConfig"/> </bean>

  註意把Bean的位置,這些Bean不能寫到SpringMVC的配置文件裏,因為對Session的管理是Spring父容器來完成的,SpringMVC是Spring容器的子容器,父容器看不到子容器的Bean。要麽直接寫到Spring容器裏,要麽寫到一個單獨的XML配置文件裏然後Import進Spring容器裏。否則會拋出org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘springSessionRepositoryFilter‘ is defined異常。配置的Filter是一個代理對象,他需要一個真正的對象來完成Session管理,真正對象就拋出異常裏沒有找到的異常。默認情況下去Spring容器裏找該真正工作Bean,所以務必要在Spring容器裏配出該Bean。

用Redis管理Session