用Redis管理Session

时间:2023-03-08 17:47:47

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。