0
点赞
收藏
分享

微信扫一扫

spring session配置详解


 1.为什么要使用spring session?

        使用spring session后可以将session对象存储至redis中,这样在做分布式或负载均衡布署时,涉及需要进行session共享的操作,均可以正常使用,
        由于session对象存储于redis中,即使中间层服务器重启(如tomcat重启)后,session对象也不丢失.赞一个。

2.如何配置spring session?

  1.      首先在maven的pom.xml中引入对应的2个jar包:  

<dependency>

<groupId>org.springframework.session</groupId>

<artifactId>spring-session-data-redis</artifactId>

<version>1.3.0.RELEASE</version>

</dependency>


<dependency>

<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>



    2.在spring的xml配置文件中增加以下2个spring session bean对象bean: 


<context:annotation-config/>
<beanclass="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"><propertyname="maxInactiveIntervalInSeconds"value="-1"/>
<propertyname="httpSessionStrategy">
<beanclass="org.springframework.session.web.http.CookieHttpSessionStrategy">


<propertyname="cookieName"value="JSESSIONID"/> <!--该参数可以定义session传至流览器客户端中cookie的参数值-->

</bean>
</property>
</bean><beanid="jedisConnectionFactory"class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"><propertyname="port"value="${redis_port}"/>
<propertyname="hostName"value="${redis_url}"/><propertyname="database"value="${redis_database}"/>
<propertyname="timeout"value="-1"/>
</bean>

其中:${XXX}的值在properties配置文件中配置.

例如:

    redis_port=6400

    redis_url=192.168.100.20

    redis_database=0

以上配置参数在:resources/DEV/system_address.properties中配置,那spring是如何找到对应的properties文件及参数值呢?

通过在spring的xml配置文件中定义:

<context:property-placeholderlocation="classpath*:${EMOS_SOURCE_ENV}/*.properties"/>

将properties中的内容加载入系统,这里面的${EMOS_SOURCE_ENV}为操作系统的环境变量(declare -x EMOS_SOURCE_ENV="DEV"),通过配置操作系统的环境变量可以将正式机,测试机配置为不同的值。

3.配置web.xml中的filter    

<!--put this filter before all of others-->
<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>

          该filter必须在所有filter的最前面!

4. 最终写入redis中的内容如图所示:

spring session配置详解_redis



举报

相关推荐

0 条评论