搜索
首页数据库Redisnginx+tomcat怎么使用redis session共享

nginx+tomcat怎么使用redis session共享

May 30, 2023 pm 06:40 PM
redisnginxtomcat

环境准备

1、准备一台nginx服务器 ip192.168.1.133 端口81

安装过程:

#首先安装依赖:
yum -y install gcc-c++ 
yum -y install pcre pcre-devel 
yum -y install zlib zlib-devel 
yum -y install openssl openssl—devel
#注意 : 安装nginx必须使用 root 用户安装
#创建一个nginx目录
mkdir /usr/local/src/nginx
#进入到nginx目录
cd /usr/local/src/nginx
#下载或上传安装包
wget http://nginx.org/download/nginx.tar.gz 或 rz上传
#解压安装包
tar -xvf nginx.tar.gz
#进入到解压后的目录
cd nginx
# 下面 才开始正式安装
#把nginx安装到指定用户的目录
mkdir -p /ucenter/soft/nginx
#安装配置 prefix为安装目录 user为用户 group为 组
./configure --prefix=/ucenter/soft/nginx --user=ucenter --group=ucenter
#编译
make 
#安装
make install
#在linux系统中由于非root用户不能占用80端口,所以需要使普通用户以root身份启动nginx。 
cd /ucenter/soft/nginx/sbin
#把soft文件下所有的文件所属者修改为ucener -r 表示递归
chown ucenter:ucenter ./soft/ -r
#修改 ./nginx 的所属为root
chown root nginx
#让普通用户可以使用80端口,可以使用root权限启用nginx
chmod u+s nginx
#修改配置文件 在修改配置文件之前 ,要备份该文件
cd conf/
# 要注意nginx 的工作进程,一般根据cpu的核数去修改
vim nginx.conf
#关闭防火墙,打开80端口
service iptables stop
#启动nginx
./nginx
#重启nginx
./nginx -s reload
#关闭nginx
./nginx -s stop

准备一台tomcat服务器,先准备java环境,安装jdk步骤省略

然后分别安装3个tomcat 服务器ip地址:192.168.1.143,tomcat1 8080端口,tomcat2 8081端口,tomcat3 8082端口。

nginx+tomcat怎么使用redis session共享

apache-tomcat-7.0.64/conf/server.xml配置文件修改这三个地方,这样端口就不会冲突

<server port="8005" shutdown="shutdown">
<connector port="8080" protocol="http/1.1"
connectiontimeout="20000"
redirectport="8443" />
<connector port="8009" protocol="ajp/1.3" redirectport="8443" />

修改tomcat root目录下index.jsp,分别增加每个tomcat的标识,以及在页面上显示session id

<%--
licensed to the apache software foundation (asf) under one or more
contributor license agreements. see the notice file distributed with
this work for additional information regarding copyright ownership.
the asf licenses this file to you under the apache license, version 2.0
(the "license"); you may not use this file except in compliance with
the license. you may obtain a copy of the license at

 http://www.apache.org/licenses/license-2.0

unless required by applicable law or agreed to in writing, software
distributed under the license is distributed on an "as is" basis,
without warranties or conditions of any kind, either express or implied.
see the license for the specific language governing permissions and
limitations under the license.
--%>
<!doctype html>
<%@ page session="true" %>
<%
java.text.simpledateformat sdf = new java.text.simpledateformat("yyyy");
request.setattribute("year", sdf.format(new java.util.date()));
request.setattribute("tomcaturl", "http://tomcat.apache.org/");
request.setattribute("tomcatdocurl", "/docs/");
request.setattribute("tomcatexamplesurl", "/examples/");
%>
<html>
 <head>
  <title><%=request.getservletcontext().getserverinfo() %></title>
  <link href="favicon.ico" rel="icon" type="image/x-icon" />
  <link href="favicon.ico" rel="shortcut icon" type="image/x-icon" />
  <link href="tomcat.css" rel="stylesheet" type="text/css" />
 </head>

 <body>
  <div id="wrapper">
   <div id="navigation" class="curved container">
    <span id="nav-home"><a href="${tomcaturl}">home--<%=request.getsession().getid() %></a></span>
    <span id="nav-hosts"><a href="${tomcatdocurl}">documentation</a></span>
    <span id="nav-config"><a href="${tomcatdocurl}config/">configuration</a></span>
    <span id="nav-examples"><a href="${tomcatexamplesurl}">examples</a></span>
    <span id="nav-wiki"><a href="http://wiki.apache.org/tomcat/frontpage">wiki</a></span>
    <span id="nav-lists"><a href="${tomcaturl}lists.html">mailing lists</a></span>
    <span id="nav-help"><a href="${tomcaturl}findhelp.html">find help</a></span>
    <br />
   </div>
   <div id="asf-box">
    <h1>${pagecontext.servletcontext.serverinfo}--8080</h1>
   </div>
   <div id="upper" class="curved container">
    <div id="congrats" class="curved container">
     <h2>if you&#39;re seeing this, you&#39;ve successfully installed tomcat. congratulations!</h2>
    </div>
    <div id="notice">
     <img src="tomcat.png" alt="[tomcat logo]" />
     <div id="tasks">
      <h3>recommended reading:</h3>
      <h4><a href="${tomcatdocurl}security-howto.html">security considerations how-to</a></h4>
      <h4><a href="${tomcatdocurl}manager-howto.html">manager application how-to</a></h4>
      <h4><a href="${tomcatdocurl}cluster-howto.html">clustering/session replication how-to</a></h4>
     </div>
    </div>
    <div id="actions">
     <div>
      <a class="container shadow" href="/manager/status"><span>server status</span></a>
     </div>
     <div>
      <a class="container shadow" href="/manager/html"><span>manager app</span></a>
     </div>
     <div>
      <a class="container shadow" href="/host-manager/html"><span>host manager</span></a>
     </div>
    </div>
    <!--
    <br />
    -->
    <br />
   </div>
   <div id="middle" class="curved container">
    <h3>developer quick start</h3>
    <div>
     <div>
      <p><a href="${tomcatdocurl}setup.html">tomcat setup</a></p>
      <p><a href="${tomcatdocurl}appdev/">first web application</a></p>
     </div>
    </div>
    <div>
     <div>
      <p><a href="${tomcatdocurl}realm-howto.html">realms & aaa</a></p>
      <p><a href="${tomcatdocurl}jndi-datasource-examples-howto.html">jdbc datasources</a></p>
     </div>
    </div>
    <div>
     <div>
      <p><a href="${tomcatexamplesurl}">examples</a></p>
     </div>
    </div>
    <div>
     <div>
      <p><a href="http://wiki.apache.org/tomcat/specifications">servlet specifications</a></p>
      <p><a href="http://wiki.apache.org/tomcat/tomcatversions">tomcat versions</a></p>
     </div>
    </div>
    <br />
   </div>
   <div id="lower">
    <div id="low-manage" class="">
     <div class="curved container">
      <h3>managing tomcat</h3>
      <p>for security, access to the <a href="/manager/html">manager webapp</a> is restricted.
      users are defined in:</p>
      <pre class="brush:php;toolbar:false">$catalina_home/conf/tomcat-users.xml

in tomcat 7.0 access to the manager application is split between different users. read more...


release notes

changelog

migration guide

security notices

documentation

tomcat 7.0 documentation

tomcat 7.0 configuration

tomcat wiki

find additional important configuration information in:

$catalina_home/running.txt

developers may be interested in:

getting help

faq and mailing lists

the following mailing lists are available:


copyright ©1999-${year} apache software foundation. all rights reserved

nginx+tomcat怎么使用redis session共享

这时候 修改nginx配置文件nginx.conf,把三台tomcat的ip地址以及端口号加入进去,使用nginx做代理

#user nobody;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid  logs/nginx.pid;


events {
 worker_connections 1024;
}


http {
 include  mime.types;
 default_type application/octet-stream;

 #log_format main &#39;$remote_addr - $remote_user [$time_local] "$request" &#39;
 #     &#39;$status $body_bytes_sent "$http_referer" &#39;
 #     &#39;"$http_user_agent" "$http_x_forwarded_for"&#39;;

 #access_log logs/access.log main;

 sendfile  on;
 #tcp_nopush  on;

 #keepalive_timeout 0;
 keepalive_timeout 65;

 #gzip on;

 upstream localhost1 { 
  
   #ip_hash; 
   server 192.168.1.143:8080; 
   server 192.168.1.143:8081; 
   server 192.168.1.143:8082; 
 } 

 server {
  listen  81;
  server_name localhost;

  #charset koi8-r;

  #access_log logs/host.access.log main;

  location / {
    proxy_connect_timeout 3; 
    proxy_send_timeout  30; 
    proxy_read_timeout  30; 
    proxy_pass http://localhost1; 
  }

  #error_page 404    /404.html;

  # redirect server error pages to the static page /50x.html
  #
  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
   root html;
  }

  # proxy the php scripts to apache listening on 127.0.0.1:80
  #
  #location ~ \.php$ {
  # proxy_pass http://127.0.0.1;
  #}

  # pass the php scripts to fastcgi server listening on 127.0.0.1:9000
  #
  #location ~ \.php$ {
  # root   html;
  # fastcgi_pass 127.0.0.1:9000;
  # fastcgi_index index.php;
  # fastcgi_param script_filename /scripts$fastcgi_script_name;
  # include  fastcgi_params;
  #}

  # deny access to .htaccess files, if apache&#39;s document root
  # concurs with nginx&#39;s one
  #
  #location ~ /\.ht {
  # deny all;
  #}
 }


 # another virtual host using mix of ip-, name-, and port-based configuration
 #
 #server {
 # listen  8000;
 # listen  somename:8080;
 # server_name somename alias another.alias;

 # location / {
 #  root html;
 #  index index.html index.htm;
 # }
 #}


 # https server
 #
 #server {
 # listen  443;
 # server_name localhost;

 # ssl     on;
 # ssl_certificate  cert.pem;
 # ssl_certificate_key cert.key;

 # ssl_session_timeout 5m;

 # ssl_protocols sslv2 sslv3 tlsv1;
 # ssl_ciphers high:!anull:!md5;
 # ssl_prefer_server_ciphers on;

 # location / {
 #  root html;
 #  index index.html index.htm;
 # }
 #}

}

这时候,分别启动三台tomcat以及nginx,访问,这时候每次刷新页面,都会随机访问8080或者8081或者8082,而且页面上出现的session id也都是不一样的,我们应该如何让这三台tomcat共享session呢,我们使用redis来做。

这时候,在已经按照三台tomcat的服务器192.168.1.143上,安装redis,安装步骤如下:

$ wget http://download.redis.io/releases/redis-3.2.3.tar.gz
$ tar xzf redis-3.2.3.tar.gz
$ cd redis-3.2.3
$ make malloc=libc
#启动redis src前面是安装的路径
$ src/redis-server &

#关闭redis
src/redis-cli shutdown
#使用redis 放入键值对 key value
$ src/redis-cli
127.0.0.1:6379> set foo bar
ok
127.0.0.1:6379> get foo
"bar"
$

安装完redis之后,在三个tomcat的lib文件夹内分别上传这五个所依赖的jar,分别是

commons-pool2-2.0.jar

jedis-2.5.2.jar

tomcat-redis-session-manager1.2.jar

tomcat-juli.jar

tomcat-juli-adapters.jar

所有jar在这里了,

然后分别修个三个tomcat的context.xml文件,增加如下的配置

<?xml version=&#39;1.0&#39; encoding=&#39;utf-8&#39;?>

<context>

 <!-- default set of monitored resources -->
 <watchedresource>web-inf/web.xml</watchedresource>

 
 <!-- 这里增加redis session共享的配置 6379是redis的端口-->
 <valve classname="com.orangefunction.tomcat.redissessions.redissessionhandlervalve" /> 
 <manager classname="com.orangefunction.tomcat.redissessions.redissessionmanager" 
 host="127.0.0.1" 
 port="6379" 
 database="0" 
 maxinactiveinterval="60" /> 
</context>

这时候,分别重启三个tomcat以及nginx,查看tomcat日志之后,发现没有任何异常报错,说明我们成功了,接下来开始测试。

我们访问nginx服务器地址:

得到的是8080端口的 tomcat1 ,session id为1a0625767f27ba95ef4d5f061fe0568d 

nginx+tomcat怎么使用redis session共享

这时候按f5刷新页面,得到的是8081端口的 tomcat2 ,session id依旧是 1a0625767f27ba95ef4d5f061fe0568d

nginx+tomcat怎么使用redis session共享

再次刷新页面,得到的是8082端口的 tomcat3,session id依旧是 1a0625767f27ba95ef4d5f061fe0568d。 、

nginx+tomcat怎么使用redis session共享

这时候,说明我们搭建tomcat + nginx负载均衡 + redis session同步成功啦!

nginx帮助把我们的请求均匀的分发给三个tomcat --》tomcat1 、tomcat2以及tomcat3

 redis帮助我们同步session,这样一来,我们的服务器性能就会提高许多,任何一台tomcat发生故障后,对整体的服务都不会有影响了。

以上是nginx+tomcat怎么使用redis session共享的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
REDIS与SQL数据库:关键差异REDIS与SQL数据库:关键差异Apr 25, 2025 am 12:02 AM

Redis和SQL数据库的主要区别在于:Redis是内存数据库,适用于高性能和灵活性需求;SQL数据库是关系型数据库,适用于复杂查询和数据一致性需求。具体来说,1)Redis提供高速数据访问和缓存服务,支持多种数据类型,适用于缓存和实时数据处理;2)SQL数据库通过表格结构管理数据,支持复杂查询和事务处理,适用于电商和金融系统等需要数据一致性的场景。

REDIS:它如何充当数据存储和服务REDIS:它如何充当数据存储和服务Apr 24, 2025 am 12:08 AM

REDISACTSASBOTHADATASTOREANDASERVICE.1)ASADATASTORE,ITUSESIN-MEMORYSTOOGATOFORFOFFASTESITION,支持VariousDatharptructuresLikeKey-valuepairsandsortedsetsetsetsetsetsetsets.2)asaservice,ItprovidespunctionslikeItionitionslikepunikeLikePublikePublikePlikePlikePlikeAndluikeAndluAascriptingiationsmpleplepleclexplectiations

REDIS与其他数据库:比较分析REDIS与其他数据库:比较分析Apr 23, 2025 am 12:16 AM

Redis与其他数据库相比,具有以下独特优势:1)速度极快,读写操作通常在微秒级别;2)支持丰富的数据结构和操作;3)灵活的使用场景,如缓存、计数器和发布订阅。选择Redis还是其他数据库需根据具体需求和场景,Redis在高性能、低延迟应用中表现出色。

REDIS的角色:探索数据存储和管理功能REDIS的角色:探索数据存储和管理功能Apr 22, 2025 am 12:10 AM

Redis在数据存储和管理中扮演着关键角色,通过其多种数据结构和持久化机制成为现代应用的核心。1)Redis支持字符串、列表、集合、有序集合和哈希表等数据结构,适用于缓存和复杂业务逻辑。2)通过RDB和AOF两种持久化方式,Redis确保数据的可靠存储和快速恢复。

REDIS:了解NOSQL概念REDIS:了解NOSQL概念Apr 21, 2025 am 12:04 AM

Redis是一种NoSQL数据库,适用于大规模数据的高效存储和访问。1.Redis是开源的内存数据结构存储系统,支持多种数据结构。2.它提供极快的读写速度,适合缓存、会话管理等。3.Redis支持持久化,通过RDB和AOF方式确保数据安全。4.使用示例包括基本的键值对操作和高级的集合去重功能。5.常见错误包括连接问题、数据类型不匹配和内存溢出,需注意调试。6.性能优化建议包括选择合适的数据结构和设置内存淘汰策略。

REDIS:现实世界的用例和示例REDIS:现实世界的用例和示例Apr 20, 2025 am 12:06 AM

Redis在现实世界中的应用包括:1.作为缓存系统加速数据库查询,2.存储Web应用的会话数据,3.实现实时排行榜,4.作为消息队列简化消息传递。Redis的多功能性和高性能使其在这些场景中大放异彩。

REDIS:探索其功能和功能REDIS:探索其功能和功能Apr 19, 2025 am 12:04 AM

Redis脱颖而出是因为其高速、多功能性和丰富的数据结构。1)Redis支持字符串、列表、集合、散列和有序集合等数据结构。2)它通过内存存储数据,支持RDB和AOF持久化。3)从Redis6.0开始引入多线程处理I/O操作,提升了高并发场景下的性能。

Redis是SQL还是NOSQL数据库?答案解释了Redis是SQL还是NOSQL数据库?答案解释了Apr 18, 2025 am 12:11 AM

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能