Spring Session + Redis实现分布式Session共享

通常情况下,Tomcat、Jetty等Servlet容器,会默认将Session保存在内存中。如果是单个服务器实例的应用,将Session保存在服务器内存中是一个非常好的方案。但是这种方案有一个缺点,就是不利于扩展。

目前越来越多的应用采用分布式部署,用于实现高可用性和负载均衡等。那么问题来了,如果将同一个应用部署在多个服务器上通过负载均衡对外提供访问,如何实现Session共享?

实际上实现Session共享的方案很多,其中一种常用的就是使用Tomcat、Jetty等服务器提供的Session共享功能,将Session的内容统一存储在一个数据库(如MySQL)或缓存(如Redis)中。我在以前的一篇博客中有介绍如何配置Jetty的Session存储在MySQL或MongoDB中。

本文主要介绍另一种实现Session共享的方案,不依赖于Servlet容器,而是Web应用代码层面的实现,直接在已有项目基础上加入Spring Session框架来实现Session统一存储在Redis中。如果你的Web应用是基于Spring框架开发的,只需要对现有项目进行少量配置,即可将一个单机版的Web应用改为一个分布式应用,由于不基于Servlet容器,所以可以随意将项目移植到其他容器。

Maven依赖

在项目中加入Spring Session的相关依赖包,包括Spring Data Redis、Jedis、Apache Commons Pool:

<!– Jedis –><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.0</version></dependency><!– Spring Data Redis –><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>1.7.3.RELEASE</version></dependency><!– Spring Session –><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session</artifactId><version>1.2.2.RELEASE</version></dependency><!– Apache Commons Pool –><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.4.2</version></dependency>配置Filter

在web.xml中加入以下过滤器,注意如果web.xml中有其他过滤器,一般情况下Spring Session的过滤器要放在第一位。

<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><dispatcher>REQUEST</dispatcher><dispatcher>ERROR</dispatcher></filter-mapping>Spring配置文件<bean class=”org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration”/><bean class=”org.springframework.data.redis.connection.jedis.JedisConnectionFactory”><property name=”hostName” value=”localhost” /><property name=”password” value=”your-password” /><property name=”port” value=”6379″ /><property name=”database” value=”10″ /></bean>

只需要以上简单的配置,至此为止即已经完成Web应用Session统一存储在Redis中,可以说是及其简单。

解决Redis云服务Unable to configure Redis to keyspace notifications异常

如果是自建服务器搭建Redis服务,以上已经完成了Spring Session配置,这一节就不用看了。不过很多公司为了稳定性、减少运维成本,会选择使用Redis云服务,例如阿里云数据库Redis版、腾讯云存储Redis等。使用过程中会出现异常:

Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘enableRedisKeyspaceNotificationsInitializer’ defined in class path resource [org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.class]:Invocation of init method failed; nested exception is java.lang.IllegalStateException: Unable to configure Redis to keyspace notifications.See #api-redisoperationssessionrepository-sessiondestroyedeventCaused by: redis.clients.jedis.exceptions.JedisDataException: ERR unknown command config没有朋友的人生是孤独的,不完整的,可是,因为生活的忙碌,

Spring Session + Redis实现分布式Session共享

相关文章:

你感兴趣的文章:

标签云: