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

    

相關文章
相關標籤/搜索