目前市面上实现session共享的方案有不少,其中比较经常使用的是使用Tomcat、Jetty等web服务器提供的session共享功能,以此将session内容统一存放在数据库(如mysql)或者缓存(redis)中;另一种方案不依赖于servlet容器,而是web应用代码层面上的实现,并且操做极其简便,只须要在已有项目基础上加入spring-session框架和redis就可实现session共享。java
前一种session共享方案依赖servlet容器,如部署使用的是tomcat时须要修改tomcat的相关配置;后一种方案适用于发布容器不固定,例如使用docker做为发布容器,每次从新部署都会从新建立容器,tomcat的配置也要从新修改,相对比较麻烦。mysql
本文主要讲述第二种session共享方案【maven项目为例】。web
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session</artifactId> <version>1.2.2.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.4.2</version> </dependency>
2.修改spring配置文件redis
添加如下配置,表明spring-session将存放在redis中,其中maxInactiveIntervalInSeconds表示session存放在redis的过时时间,默认1800秒。spring
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> <property name="maxInactiveIntervalInSeconds" value="43200"/> </bean>
添加redis配置:sql
单节点redis>docker
<bean 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.password}" /> </bean>
集群redis>数据库
<bean id="sentinelConfig" class="org.springframework.data.redis.connection.RedisSentinelConfiguration"> <constructor-arg name="master" value="${redis.master}" /> <constructor-arg name="sentinelHostAndPorts"> <set> <value>127.0.0.1:2679</value><!--配置redis哨兵--> <value>127.0.0.1:2678</value> </set> </constructor-arg> </bean> <bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <constructor-arg ref="sentinelConfig" /> <property name="password" value="${redis.password}"/> </bean>
3.修改web.xml 配置apache
<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>
到此,全部工做均已完成,启动项目便可检验session是否实现共享。 项目中使用的redis server版本必须2.8+ 。缓存
喜欢的朋友能够关注个人公众号,更多精彩分享尽在“Java实战”。