发表于 2016-09-29

通常情况下,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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!-- 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的过滤器要放在第一位。

1
2
3
4
5
6
7
8
9
10
<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配置文件

1
2
3
4
5
6
7
<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等。使用过程中会出现异常:

1
2
3
4
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 http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedevent
Caused by: redis.clients.jedis.exceptions.JedisDataException: ERR unknown command config

实际上这种异常发生的原因是,很多Redis云服务提供商考虑到安全因素,会禁用掉Redis的config命令:
禁用config命令
在错误提示链接的文档中,可以看到Redis需要以下的配置:

1
redis-cli config set notify-keyspace-events Egx

文档地址:
http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedevent

首先要想办法给云服务Redis加上这个配置。

部分Redis云服务提供商可以在对应的管理后台配置:
配置notify-keyspace-events
如果不能在后台配置,可以通过工单联系售后工程师帮忙配置,例如阿里云:
阿里云工单

完成之后,还需要在Spring配置文件中加上一个配置,让Spring Session不再执行config命令:

However, in a secured Redis enviornment the config command is disabled. This means that Spring Session cannot configure Redis Keyspace events for you. To disable the automatic configuration add ConfigureRedisAction.NO_OP as a bean.

配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"> <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> <!-- 让Spring Session不再执行config命令 -->
<util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/> </beans>

Spring Session + Redis实现分布式Session共享的更多相关文章

  1. 基于Spring Boot/Spring Session/Redis的分布式Session共享解决方案

    分布式Web网站一般都会碰到集群session共享问题,之前也做过一些Spring3的项目,当时解决这个问题做过两种方案,一是利用nginx,session交给nginx控制,但是这个需要额外工作较多 ...

  2. Spring Boot 应用使用spring session+redis启用分布式session后,如何在配置文件里设置应用的cookiename、session超时时间、redis存储的namespace

    现状 项目在使用Spring Cloud搭建微服务框架,其中分布式session采用spring session+redis 模式 需求 希望可以在配置文件(application.yml)里设置应用 ...

  3. 使用Spring Session和Redis解决分布式Session跨域共享问题

    http://blog.csdn.net/xlgen157387/article/details/57406162 使用Spring Session和Redis解决分布式Session跨域共享问题

  4. 170222、使用Spring Session和Redis解决分布式Session跨域共享问题

    使用Spring Session和Redis解决分布式Session跨域共享问题 原创 2017-02-27 徐刘根 Java后端技术 前言 对于分布式使用Nginx+Tomcat实现负载均衡,最常用 ...

  5. Tornado 自定义session,与一致性哈希 ,基于redis 构建分布式 session框架

    Tornado 自定义session,与一致性哈希 ,基于redis 构建分布式 session import tornado.ioloop import tornado.web from myhas ...

  6. 使用SpringSession和Redis解决分布式Session共享问题

    SpringSession优势 遵循servlet规范,同样方式获取session,对应用代码无侵入且对于developers透明化 关键点在于做到透明和兼容 接口适配:仍然使用HttpServlet ...

  7. SpringBoot搭建基于Apache Shiro+Redis的分布式Session共享功能

    我们在上一遍文档中已经完成了Shiro验证功能.(http://www.cnblogs.com/nbfujx/p/7773789.html),在此基础上我们将完成分布式Session共享功能. Red ...

  8. springboot+redis实现分布式session共享

    官方文档,它是spring session项目的redis相关的一个子文档:https://docs.spring.io/spring-session/docs/2.0.0.BUILD-SNAPSHO ...

  9. 【Redis】分布式Session

    一.问题引出 1.1 Session的原理 1.2 问题概述 二.解决方案 三.代码实现-使用Token代替Session 3.1 Service 3.2 TokenController 一.问题引出 ...

随机推荐

  1. python学习笔记011——闭包

    1 定义 定义:在计算机科学中,闭包是词法闭包的简称,是引用了自由变量的函数 简单地说:闭包就是能够读取其他函数内部变量的函数,闭包是将函数内部和函数外部连接起来的桥梁.——来源百度百科 2 描述 形 ...

  2. codeforces #296 div2 (527C) STL中set的运用

    题意:在一块H*M的玻璃上每次划一刀(仅仅能水平或竖直).输出每次划开之后剩下的玻璃中面积最大的一块的面积. 做题的时候.觉得这么大的数据量,有每次查询输出,应该是数据结构的内容. 这道题能够用STL ...

  3. 查看mysql日志

    1.首先确认你日志是否启用了 MySQL>show variables like 'log_bin'; 2.如果启用了,即ON那日志文件就在MySQL的安装目录的data目录下 3.怎样知道当前 ...

  4. 自定义相机下使用clippingNode注意事项

    调用完clippingNode->setCameraMask(myCameraMask)后,还需要clipNode->getStencil()->setCameraMask(myCa ...

  5. Android 开发之 bindService() 通信

    Service 启动方式有两种 startService(intent) bindService(intent,conn,Context.BIND_AUTO_CREATE) startService( ...

  6. Ip地址和子网掩码和CIDR无间别域间路由

    开始,网络的制定者将网络划分为A,B,C三种网络,想这个样子: A类网:  xxx.0.0.0         子网掩码:255.0.0.0 xxx.0.0.0/8 //后面的数字代表网络地址的字段 ...

  7. 关于UI测试

    分为UI逻辑测试和UI显示测试两部分.要根据不同的面板状态进行测试 状态 -UI逻辑 -显示测试 一般优先做UI逻辑测试,后做显示测试.因为显示内容要经常变动,而且看的始终比代码测的准.去测显示测试会 ...

  8. 《ZedBoard各种资料网址备份记录》

    转载来自于:http://http//www.eefocus.com/crazybingo/blog/2013-02/289101_ab4c8.html 1. Xilinx FPGA相关连接 1) X ...

  9. 【Android】3.0 第3章 百度地图及其应用--预备知识

    分类:C#.Android.VS2015.百度地图应用: 创建日期:2016-02-04 一.概述 这一章先来点有意思的百度地图应用示例,然后再分章详细介绍用C#开发Android App的各种基本技 ...

  10. 深入理解node.js的module.export 和 export方法的区别

    你肯定非常熟悉nodejs模块中的exports对象,你可以用它创建你的模块.例如:(假设这是rocker.js文件) exports.name = function() { console.log( ...