發現有的項目中使用了SpringSession技術,使用普通Session可以達到多個工程共享Session的目的,感覺很有意義,於是自己在本地搭建了一套demo,來測試一下。
本篇博客借鑑了ssm集成springSession解決session會話丟失,感謝作者分享。
SpringSession的原理其實很簡單,就是把HttpSession放入了redis中,所有的seesion操作,操作的都是redis中的這個session,由此達到了session共享的目的。
好了,原理性的東西目前就瞭解了這麼多。下面我們看一下如何在ssm工程中引入SpringSession技術。
1.引入相關依賴
<!-- springsession-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
2.web.xml配置
配置Spring的filter代理類,將filter的生命週期交予Spring管理。
<!--SpingSession-->
<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>
3.Spring配置文件配置
引入SpringSession配置類,我們可以根據項目的需要配置一下SpringSession,比如:我在例子中就配置了SpringSession在redis中的命名空間
另外一個,就是添加了redis的連接工廠類,因爲SpringSession的共享是依賴redis的,所以需要引入redis
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration" p:redisNamespace="mvc"/>
<bean name="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.hostname}"/>
<property name="port" value="${redis.port}"/>
<property name="password" value="${redis.password}"/>
</bean>
4.使用SpringSession
下面,我們就可以使用SpringSession了,使用SpringSession和使用普通的HttpSession一樣,如下例:
@RequestMapping(value = "/get",method = RequestMethod.GET)
public String getConfigName(HttpServletRequest request,HttpSession session){
log.info("進入get方法,[{}]",request.getRequestURI());
session.getAttribute("configName");
return (String)session.getAttribute("configName");
}