基于 Redis 的 Session 共享示例

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


在单机情况下,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 赞助。

    284 引用 • 247 回帖 • 182 关注

相关帖子

欢迎来到这里!

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

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

推荐标签 标签

  • Jenkins

    Jenkins 是一套开源的持续集成工具。它提供了非常丰富的插件,让构建、部署、自动化集成项目变得简单易用。

    51 引用 • 37 回帖
  • SVN

    SVN 是 Subversion 的简称,是一个开放源代码的版本控制系统,相较于 RCS、CVS,它采用了分支管理系统,它的设计目标就是取代 CVS。

    29 引用 • 98 回帖 • 693 关注
  • 分享

    有什么新发现就分享给大家吧!

    242 引用 • 1746 回帖 • 1 关注
  • frp

    frp 是一个可用于内网穿透的高性能的反向代理应用,支持 TCP、UDP、 HTTP 和 HTTPS 协议。

    15 引用 • 7 回帖 • 7 关注
  • Pipe

    Pipe 是一款小而美的开源博客平台。Pipe 有着非常活跃的社区,可将文章作为帖子推送到社区,来自社区的回帖将作为博客评论进行联动(具体细节请浏览 B3log 构思 - 分布式社区网络)。

    这是一种全新的网络社区体验,让热爱记录和分享的你不再感到孤单!

    131 引用 • 1114 回帖 • 150 关注
  • 链滴

    链滴是一个记录生活的地方。

    记录生活,连接点滴

    131 引用 • 3639 回帖
  • CentOS

    CentOS(Community Enterprise Operating System)是 Linux 发行版之一,它是来自于 Red Hat Enterprise Linux 依照开放源代码规定释出的源代码所编译而成。由于出自同样的源代码,因此有些要求高度稳定的服务器以 CentOS 替代商业版的 Red Hat Enterprise Linux 使用。两者的不同在于 CentOS 并不包含封闭源代码软件。

    238 引用 • 224 回帖 • 1 关注
  • V2Ray
    1 引用 • 15 回帖
  • 区块链

    区块链是分布式数据存储、点对点传输、共识机制、加密算法等计算机技术的新型应用模式。所谓共识机制是区块链系统中实现不同节点之间建立信任、获取权益的数学算法 。

    91 引用 • 751 回帖
  • 30Seconds

    📙 前端知识精选集,包含 HTML、CSS、JavaScript、React、Node、安全等方面,每天仅需 30 秒。

    • 精选常见面试题,帮助您准备下一次面试
    • 精选常见交互,帮助您拥有简洁酷炫的站点
    • 精选有用的 React 片段,帮助你获取最佳实践
    • 精选常见代码集,帮助您提高打码效率
    • 整理前端界的最新资讯,邀您一同探索新世界
    488 引用 • 383 回帖 • 2 关注
  • 电影

    这是一个不能说的秘密。

    120 引用 • 597 回帖 • 2 关注
  • JSON

    JSON (JavaScript Object Notation)是一种轻量级的数据交换格式。易于人类阅读和编写。同时也易于机器解析和生成。

    51 引用 • 190 回帖
  • 面试

    面试造航母,上班拧螺丝。多面试,少加班。

    324 引用 • 1395 回帖 • 2 关注
  • GitBook

    GitBook 使您的团队可以轻松编写和维护高质量的文档。 分享知识,提高团队的工作效率,让用户满意。

    3 引用 • 8 回帖 • 1 关注
  • OpenShift

    红帽提供的 PaaS 云,支持多种编程语言,为开发人员提供了更为灵活的框架、存储选择。

    14 引用 • 20 回帖 • 602 关注
  • GitLab

    GitLab 是利用 Ruby 一个开源的版本管理系统,实现一个自托管的 Git 项目仓库,可通过 Web 界面操作公开或私有项目。

    46 引用 • 72 回帖
  • 倾城之链
    23 引用 • 66 回帖 • 96 关注
  • 运维

    互联网运维工作,以服务为中心,以稳定、安全、高效为三个基本点,确保公司的互联网业务能够 7×24 小时为用户提供高质量的服务。

    148 引用 • 257 回帖 • 1 关注
  • 笔记

    好记性不如烂笔头。

    303 引用 • 777 回帖
  • Hprose

    Hprose 是一款先进的轻量级、跨语言、跨平台、无侵入式、高性能动态远程对象调用引擎库。它不仅简单易用,而且功能强大。你无需专门学习,只需看上几眼,就能用它轻松构建分布式应用系统。

    9 引用 • 17 回帖 • 597 关注
  • Netty

    Netty 是一个基于 NIO 的客户端-服务器编程框架,使用 Netty 可以让你快速、简单地开发出一个可维护、高性能的网络应用,例如实现了某种协议的客户、服务端应用。

    49 引用 • 33 回帖 • 21 关注
  • Kubernetes

    Kubernetes 是 Google 开源的一个容器编排引擎,它支持自动化部署、大规模可伸缩、应用容器化管理。

    108 引用 • 54 回帖 • 1 关注
  • Hexo

    Hexo 是一款快速、简洁且高效的博客框架,使用 Node.js 编写。

    21 引用 • 140 回帖 • 25 关注
  • JVM

    JVM(Java Virtual Machine)Java 虚拟机是一个微型操作系统,有自己的硬件构架体系,还有相应的指令系统。能够识别 Java 独特的 .class 文件(字节码),能够将这些文件中的信息读取出来,使得 Java 程序只需要生成 Java 虚拟机上的字节码后就能在不同操作系统平台上进行运行。

    180 引用 • 120 回帖
  • OkHttp

    OkHttp 是一款 HTTP & HTTP/2 客户端库,专为 Android 和 Java 应用打造。

    16 引用 • 6 回帖 • 54 关注
  • wolai

    我来 wolai:不仅仅是未来的云端笔记!

    1 引用 • 11 回帖
  • 持续集成

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

    14 引用 • 7 回帖 • 1 关注