通常情況下,Tomcat、Jetty等Servlet容器,會默認將Session保存在內存中。如果是單個服務器實例的應用,將Session保存在服務器內存中是一個非常好的方案。但是這種方案有一個缺點,就是不利於擴展。
目前越來越多的應用采用分布式部署,用於實現高可用性和負載均衡等。那么問題來了,如果將同一個應用部署在多個服務器上通過負載均衡對外提供訪問,如何實現Session共享?
實際上實現Session共享的方案很多,其中一種常用的就是使用Tomcat、Jetty等服務器提供的Session共享功能,將Session的內容統一存儲在一個數據庫(如MySQL)或緩存(如Redis)中。
本文主要介紹另一種實現Session共享的方案,不依賴於Servlet容器,而是Web應用代碼層面的實現,直接在已有項目基礎上加入Spring Session框架來實現Session統一存儲在Redis中。如果你的Web應用是基於Spring框架開發的,只需要對現有項目進行少量配置,即可將一個單機版的Web應用改為一個分布式應用,由於不基於Servlet容器,所以可以隨意將項目移植到其他容器。
Maven依賴
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>1.2.2.RELEASE</version> </dependency>
配置Filter
在web.xml中加入以下過濾器,注意如果web.xml中有其他過濾器,一般情況下Spring Session的過濾器要放在第一位。ContextLoaderListener是必須要添加的,不然啟動會報錯。
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring/*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<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>
Spring配置文件
spring-redis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd "> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig" p:maxIdle="300" p:maxWaitMillis="1000" p:testOnBorrow="true"> </bean> <!-- 添加RedisHttpSessionConfiguration用於session共享 --> <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:hostName="192.168.1.143" p:port="6379" p:password="123456" p:poolConfig-ref="poolConfig" p:usePool="true" p:database="1" p:timeout="3000"/> </beans>
spring-mvc.xml配置文件增加以下配置,就是把上面的配置文件導入進去
<import resource="classpath:redis/spring-redis.xml"/>
只需要以上簡單的配置,至此為止即已經完成Web應用Session統一存儲在Redis中,可以說是及其簡單。
參考網站:
redis搭建: http://xxgblog.com/2016/09/29/spring-session-redis/ 按照此方法有jar依賴沖突 按照評論的去掉那個依賴即可
web.xml配置報錯:http://blog.csdn.net/zuoyexingchennn/article/details/50426869
