SpringMVC集成Spring-Session进行分布式管理

项目使用的是SpringMVC+hibernate,遵从老大的意见使用Spring-Session进行处理session,用redis托管Session。下面正式记录下处理方法。 web

    1.若是项目以前没有整合过spring-data-redis的话,这一步须要先作,在maven中添加这几个依赖: redis


<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-data-redis</artifactId>
			<version>1.0.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session</artifactId>
			<version>1.0.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>com.orange.redis-embedded</groupId>
			<artifactId>embedded-redis</artifactId>
			<version>0.6</version>
		</dependency>



2. 再在applicationContext.xml中添加如下bean,用于定义redis的链接池和初始化redis模版操做类,自行替换其中的相关变量。


<!-- redis -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
</bean>
 
<bean id="jedisConnectionFactory"
    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="hostName" value="${redis.host}" />
    <property name="port" value="${redis.port}" />
    <property name="password" value="${redis.pass}" />
    <property name="timeout" value="${redis.timeout}" />
    <property name="poolConfig" ref="jedisPoolConfig" />
    <property name="usePool" value="true" />
</bean>
 
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
    <property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
 
<!-- 将session放入redis -->
<bean id="redisHttpSessionConfiguration"
class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
    <property name="maxInactiveIntervalInSeconds" value="1800" />
</bean>



3. 而后是在web.xml中添加一个session代理filter,经过这个filter来包装Servlet的getSession()。将配置放置到最前面,让其具备最优先地位。


<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>



#------------ redis ------------
redis.host=192.168.1.174
redis.port=6379
redis.pass=
redis.timeout=1800



接下来就是各类处理,request.getSession.setAttribute等


测试环节: spring

   1. 开启两个tomcat,eg:localhost:8888和localhot:8080 而后运行起来。
浏览器

   2.开开一个浏览器(必定注意使用同一个浏览器),打开8080的一个tab,而后登陆,进入我的中心(须要登陆才能进入的界面)。登陆以后,将链接拷贝到另一个浏览器tab,端口改成8888,发现不用登陆就已经登陆进去了。
tomcat

   3.查看redis,Mac下可使用rdm工具 session

    

相关文章
相关标签/搜索