基于 Redis 的 Session 共享示例

本贴最后更新于 2953 天前,其中的信息可能已经天翻地覆


在单机情况下,Session可由部署在服务器上的Web容器来管理 (如Tomcat、JBoss)。

在负载均衡的集群环境下,负载均衡可能将请求分发到不同的服务器上去,在这种情况,需要将有状态的session统一管理起来。

本文将给出一个简单的示例,将session存放到Redis统一管理。因为只是一个示例,所以Nginx只用1台,Tomcat使用2台,Redis一个或者简单的主从。

环境准备

准备Redis

下载redis-3.2.3.tar.gz (Redis.io下载)

解压缩redis

tar -zvxf redis-3.2.3.tar.gz


 

将解压缩后的redis文件名改成好记点的6379 (可以不重命名)。

然后使用make && make install 完成安装。

[root@dev18 redis]# mv redis-3.2.3 6379 [root@dev18 redis]# cd 6379 [root@dev18 6379]# make && make install 

安装成功之后,出现如下显示:

因为本版本使用的Redis版本是3.2.3, 在这个版本中,有protected mode的属性(默认是yes),进入6379目录,修改redis.conf配置文件。从而,其它网段的程序可以去访问,否则可能会出现如下的错误。

Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside. at redis.clients.jedis.Protocol.processError(Protocol.java:117) at redis.clients.jedis.Protocol.process(Protocol.java:151) at redis.clients.jedis.Protocol.read(Protocol.java:205) at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:297) at redis.clients.jedis.Connection.getIntegerReply(Connection.java:222) at redis.clients.jedis.Jedis.sadd(Jedis.java:1057) at jedis.example.Main.main(Main.java:36) 

修改后保存。

进入src目录,启动Redis服务

[root@dev18 6379]# cd src [root@dev18 src]# ./redis-server 

成功启动显示如下:

[root@dev18 src]# ./redis-server 10051:C 22 Dec 09:50:59.653 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf _._ _.-``__ ''-._ _.-`` `.  `_. ''-._ Redis 3.2.3 (00000000/0) 64 bit
  .-`` .-```.  ```\/ _.,_ ''-._ ( '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._ `._    /     _.-' |     PID: 10051
  `-._ `-._  `-./ _.-'    _.-' |`-._`-._ `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._ `-._`-.__.-'_.-' _.-' |`-._`-._    `-.__.-' _.-'_.-'|                                  
 | `-._`-._ _.-'_.-' | `-._    `-._`-.__.-'_.-'    _.-' `-._ `-.__.-'    _.-' `-._ _.-'                                           
              `-.__.-' 10051:M 22 Dec 09:50:59.656 # Server started, Redis version 3.2.3 10051:M 22 Dec 09:50:59.656 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect. 10051:M 22 Dec 09:50:59.656 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled. 10051:M 22 Dec 09:50:59.656 * The server is now ready to accept connections on port 6379 

准备Tomcat

下载tomcat,并解压缩为两个tomcat,并修改各自server.xml中的端口,保证两者不冲突。

本示例中,tomcat_1的端口为8082

<Connector port="8082" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />

tomcat_2的端口为8083

<Connector port="8083" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />

准备Session-Manager

大家可以通过如下路径获取Session-Manager的jar包和相关的依赖包,包括common-pool2和Jedis。

https://pan.baidu.com/s/1geZVozx

下载好之后,我们首先将这三个jar包,放到Tomcat目录下的lib文件夹中。

配置Context.xml,添加如下内容,具体的host和port由自己的环境决定。

<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" /> <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager" host="xxx.xx.xx.xxx" port="6379" database="0" maxInactiveInterval="60" /> 

然后准备一个项目,为了方便,我直接将测试的war中的文件替换了Tomcat_Home/webapps中的ROOT的内容。也可以通过tomcat自带的examples示例来测试session。

如:http://localhost:8082/examples/servlets/servlet/SessionExample

至此,两个测试的tomat就准备好了,并且已经配置了session管理,由redis来存储。接下来,我们就需要一个Nginx用于负载,配置两个tomcat的信息即可。

准备Nginx

下载Nginx,解压,然后进入Nginx的conf目录,修改nginx.conf文件内容,找到http的部分,添加upstream,就是我们上述提到的两个tomcat。

http { upstream tomcat  { server localhost:8082; server localhost:8083;  
	}

本文Nginx的端口为8899, 自己设定了一个。

server { listen 8899;

至此Nginx, Tomcat, Session-Manager, Redis相关的环境就全部准备好了。

接下来,要做的就是启动Nginx, Tomcat, Redis,来看看 session是否存入到Redis中,自己的Web工程能不能正常运行等。

启动Nginx和Tomcat

进入NGINX_HOME/使用 nginx命令启动Nginx服务器。

进入两个tomcat_1和tomcat_2,分别启动tomcat。登录自己在ROOT中放置的WEB工程,可以看到session在Redis中存储下来了。

通过Redis-Desktop Manager查看Redis中session的信息。

配置一个Redis从服务器

通过Redis-Desktop Manager查看Redis中session的信息。

为上面的6379主服务器配置一个从服务器6380。

在6380的redis.conf中指定 是6379的slave,如:

slaveof 127.0.0.1 6379

启动从服务器:

[root@dev18 src]# ./redis-server ../redis.conf  _._ _.-``__ ''-._ _.-``    `.  `_. ''-._ Redis 3.2.3 (00000000/0) 64 bit
  .-`` .-```.  ```\/ _.,_ ''-._ ( '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6380
 |    `-._   `._    /     _.-' | PID: 14302 `-._ `-._ `-./ _.-'    _.-' |`-._`-._ `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-' |`-._`-._ `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-' `-._ `-.__.-'    _.-' `-._ _.-'                                           
              `-.__.-' 14302:S 22 Dec 12:02:55.810 # Server started, Redis version 3.2.3 14302:S 22 Dec 12:02:55.810 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect. 14302:S 22 Dec 12:02:55.810 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled. 14302:S 22 Dec 12:02:55.810 * The server is now ready to accept connections on port 6380 14302:S 22 Dec 12:02:55.810 * Connecting to MASTER 127.0.0.1:6379 14302:S 22 Dec 12:02:55.810 * MASTER <-> SLAVE sync started 14302:S 22 Dec 12:02:55.810 * Non blocking connect for SYNC fired the event. 14302:S 22 Dec 12:02:55.811 * Master replied to PING, replication can continue... 14302:S 22 Dec 12:02:55.811 * Partial resynchronization not possible (no cached master) 14302:S 22 Dec 12:02:55.815 * Full resync from master: c5038d1cbe197bbd8c8fee0e719370eac42bd6bc:1 14302:S 22 Dec 12:02:55.865 * MASTER <-> SLAVE sync: receiving 2741 bytes from master 14302:S 22 Dec 12:02:55.865 * MASTER <-> SLAVE sync: Flushing old data 14302:S 22 Dec 12:02:55.865 * MASTER <-> SLAVE sync: Loading DB in memory 14302:S 22 Dec 12:02:55.866 * MASTER <-> SLAVE sync: Finished with success

使用Redis-Desktop Manager

可以看到,主服务6379和从服务6380都包含session的相关信息。

  • Redis

    Redis 是一个开源的使用 ANSI C 语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value 数据库,并提供多种语言的 API。从 2010 年 3 月 15 日起,Redis 的开发工作由 VMware 主持。从 2013 年 5 月开始,Redis 的开发由 Pivotal 赞助。

    286 引用 • 248 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...

推荐标签 标签

  • WiFiDog

    WiFiDog 是一套开源的无线热点认证管理工具,主要功能包括:位置相关的内容递送;用户认证和授权;集中式网络监控。

    1 引用 • 7 回帖 • 612 关注
  • ngrok

    ngrok 是一个反向代理,通过在公共的端点和本地运行的 Web 服务器之间建立一个安全的通道。

    7 引用 • 63 回帖 • 647 关注
  • CSS

    CSS(Cascading Style Sheet)“层叠样式表”是用于控制网页样式并允许将样式信息与网页内容分离的一种标记性语言。

    199 引用 • 541 回帖 • 1 关注
  • Caddy

    Caddy 是一款默认自动启用 HTTPS 的 HTTP/2 Web 服务器。

    12 引用 • 54 回帖 • 166 关注
  • Windows

    Microsoft Windows 是美国微软公司研发的一套操作系统,它问世于 1985 年,起初仅仅是 Microsoft-DOS 模拟环境,后续的系统版本由于微软不断的更新升级,不但易用,也慢慢的成为家家户户人们最喜爱的操作系统。

    226 引用 • 476 回帖
  • 音乐

    你听到信仰的声音了么?

    62 引用 • 512 回帖 • 1 关注
  • C

    C 语言是一门通用计算机编程语言,应用广泛。C 语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。

    85 引用 • 165 回帖 • 1 关注
  • 学习

    “梦想从学习开始,事业从实践起步” —— 习近平

    172 引用 • 516 回帖
  • Node.js

    Node.js 是一个基于 Chrome JavaScript 运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。Node.js 使用事件驱动, 非阻塞 I/O 模型而得以轻量和高效。

    139 引用 • 269 回帖 • 1 关注
  • Outlook
    1 引用 • 5 回帖
  • SOHO

    为成为自由职业者在家办公而努力吧!

    7 引用 • 55 回帖
  • 持续集成

    持续集成(Continuous Integration)是一种软件开发实践,即团队开发成员经常集成他们的工作,通过每个成员每天至少集成一次,也就意味着每天可能会发生多次集成。每次集成都通过自动化的构建(包括编译,发布,自动化测试)来验证,从而尽早地发现集成错误。

    15 引用 • 7 回帖
  • CAP

    CAP 指的是在一个分布式系统中, Consistency(一致性)、 Availability(可用性)、Partition tolerance(分区容错性),三者不可兼得。

    12 引用 • 5 回帖 • 638 关注
  • Openfire

    Openfire 是开源的、基于可拓展通讯和表示协议 (XMPP)、采用 Java 编程语言开发的实时协作服务器。Openfire 的效率很高,单台服务器可支持上万并发用户。

    6 引用 • 7 回帖 • 100 关注
  • 百度

    百度(Nasdaq:BIDU)是全球最大的中文搜索引擎、最大的中文网站。2000 年 1 月由李彦宏创立于北京中关村,致力于向人们提供“简单,可依赖”的信息获取方式。“百度”二字源于中国宋朝词人辛弃疾的《青玉案·元夕》词句“众里寻他千百度”,象征着百度对中文信息检索技术的执著追求。

    63 引用 • 785 回帖 • 108 关注
  • jsDelivr

    jsDelivr 是一个开源的 CDN 服务,可为 npm 包、GitHub 仓库提供免费、快速并且可靠的全球 CDN 加速服务。

    5 引用 • 31 回帖 • 100 关注
  • Linux

    Linux 是一套免费使用和自由传播的类 Unix 操作系统,是一个基于 POSIX 和 Unix 的多用户、多任务、支持多线程和多 CPU 的操作系统。它能运行主要的 Unix 工具软件、应用程序和网络协议,并支持 32 位和 64 位硬件。Linux 继承了 Unix 以网络为核心的设计思想,是一个性能稳定的多用户网络操作系统。

    952 引用 • 944 回帖
  • 智能合约

    智能合约(Smart contract)是一种旨在以信息化方式传播、验证或执行合同的计算机协议。智能合约允许在没有第三方的情况下进行可信交易,这些交易可追踪且不可逆转。智能合约概念于 1994 年由 Nick Szabo 首次提出。

    1 引用 • 11 回帖 • 2 关注
  • JWT

    JWT(JSON Web Token)是一种用于双方之间传递信息的简洁的、安全的表述性声明规范。JWT 作为一个开放的标准(RFC 7519),定义了一种简洁的,自包含的方法用于通信双方之间以 JSON 的形式安全的传递信息。

    20 引用 • 15 回帖 • 19 关注
  • NGINX

    NGINX 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 NGINX 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,第一个公开版本 0.1.0 发布于 2004 年 10 月 4 日。

    315 引用 • 547 回帖
  • Python

    Python 是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用缩进来定义语句块。

    556 引用 • 675 回帖
  • etcd

    etcd 是一个分布式、高可用的 key-value 数据存储,专门用于在分布式系统中保存关键数据。

    6 引用 • 26 回帖 • 548 关注
  • RIP

    愿逝者安息!

    8 引用 • 92 回帖 • 394 关注
  • Flume

    Flume 是一套分布式的、可靠的,可用于有效地收集、聚合和搬运大量日志数据的服务架构。

    9 引用 • 6 回帖 • 652 关注
  • FFmpeg

    FFmpeg 是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。

    23 引用 • 32 回帖 • 3 关注
  • Excel
    31 引用 • 28 回帖 • 1 关注
  • Sphinx

    Sphinx 是一个基于 SQL 的全文检索引擎,可以结合 MySQL、PostgreSQL 做全文搜索,它可以提供比数据库本身更专业的搜索功能,使得应用程序更容易实现专业化的全文检索。

    1 引用 • 220 关注