데이터 베이스 Redis nginx+tomcat으로 redis 세션 공유를 사용하는 방법

nginx+tomcat으로 redis 세션 공유를 사용하는 방법

May 30, 2023 pm 06:40 PM
redis nginx tomcat

환경 준비

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 루트 디렉터리의 index.jsp를 수정하고 각 Tomcat 로고를 별도로 추가하세요. , 그리고 페이지에 세션 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;
 # }
 #}

}
로그인 후 복사

이때 각각 3개의 tomcat과 nginx를 시작하고 방문하면 페이지를 새로 고칠 때마다 무작위로 8080이나 8081 또는 8082에 액세스하게 되며 페이지에 나타나는 세션 ID도 서로 다르므로 이 3개를 어떻게 만들어야 할까요? tomcats share 세션은 redis를 사용합니다.

이때, 3개의 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를 설치한 후 3개의 tomcat lib 폴더에 5개의 종속성을 업로드합니다. commons-pool2-2.0.jar

jedis-2.5.2.jar

tomcat-redis-session-manager1.2.jar

tomcat-juli.jar

tomcat-juli-adapters .jar

모든 항아리

그런 다음 3개의 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>
로그인 후 복사

이때 3개의 tomcat과 nginx를 각각 다시 시작하세요. Tomcat 로그를 확인한 결과 예외가 보고되지 않는 것으로 나타났습니다. , 이는 성공했음을 의미하며 다음 테스트를 시작할 수 있습니다.

nginx 서버 주소를 방문합니다.

우리가 얻는 것은 포트 8080의 tomcat1이고 세션 ID는 1a0625767f27ba95ef4d5f061fe0568d입니다.


nginx+tomcat怎么使用redis session共享이 때 페이지를 새로 고치려면 f5를 누르면 tomcat2를 얻습니다. 포트 8081, s 세션 ID는 여전히 1a0625767f27ba95ef4d5f061fe0568d


nginx+tomcat怎么使用redis session共享페이지를 다시 새로 고치고 포트 8082의 tomcat3을 가져오며 세션 ID는 여전히 1a0625767f27ba95ef4d5f061fe0568d입니다. ,

nginx+tomcat怎么使用redis session共享이때, tomcat + nginx 로드 밸런싱 + redis 세션 동기화를 성공적으로 구축했다는 의미입니다!

nginx는 요청을 3개의 Tomcat에 균등하게 분배하는 데 도움이 됩니다. --》tomcat1, tomcat2 및 tomcat3

redis는 세션을 동기화하는 데 도움이 됩니다. 이러한 방식으로 Tomcat이 실패하면 서버 성능이 많이 향상됩니다. 전반적인 서비스에 영향을 미칩니다.

위 내용은 nginx+tomcat으로 redis 세션 공유를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Docker 컨테이너의 이름을 확인하는 방법 Docker 컨테이너의 이름을 확인하는 방법 Apr 15, 2025 pm 12:21 PM

단계를 따르면 Docker 컨테이너 이름을 쿼리 할 수 ​​있습니다. 모든 컨테이너 (Docker PS)를 나열하십시오. 컨테이너 목록을 필터링합니다 (GREP 명령 사용). 컨테이너 이름 ( "이름"열에 위치)을 가져옵니다.

Docker가 컨테이너를 시작하는 방법 Docker가 컨테이너를 시작하는 방법 Apr 15, 2025 pm 12:27 PM

Docker Container Startup 단계 : 컨테이너 이미지를 당기기 : "Docker Pull [Mirror Name]"을 실행하십시오. 컨테이너 생성 : "docker"[옵션] [미러 이름] [명령 및 매개 변수]를 사용하십시오. 컨테이너를 시작하십시오 : "Docker start [컨테이너 이름 또는 ID]"를 실행하십시오. 컨테이너 상태 확인 : 컨테이너가 "Docker PS"로 실행 중인지 확인하십시오.

Docker 용 컨테이너를 만드는 방법 Docker 용 컨테이너를 만드는 방법 Apr 15, 2025 pm 12:18 PM

Docker에서 컨테이너 만들기 : 1. 이미지를 당기기 : Docker Pull [Mirror Name] 2. 컨테이너 만들기 : Docker Run [옵션] [미러 이름] [명령] 3. 컨테이너 시작 : Docker Start [컨테이너 이름]

Centos redis에서 느린 쿼리 로그를 구성하는 방법 Centos redis에서 느린 쿼리 로그를 구성하는 방법 Apr 14, 2025 pm 04:54 PM

CentOS 시스템에서 Redis Slow Query 로그를 활성화하여 성능 진단 효율성을 향상시킵니다. 다음 단계는 구성을 안내합니다. 1 단계 : Redis 구성 파일 찾기 및 편집 먼저, 일반적으로 /etc/redis/redis.conf에있는 redis 구성 파일을 찾으십시오. 다음 명령으로 구성 파일을 엽니 다. sudovi/etc/redis/redis.conf 2 단계 : 구성 파일에서 느린 쿼리 로그 매개 변수 조정, 다음 매개 변수를 찾고 수정하십시오.

Redis 캐시 솔루션을 사용하여 제품 순위 목록의 요구 사항을 효율적으로 실현하는 방법은 무엇입니까? Redis 캐시 솔루션을 사용하여 제품 순위 목록의 요구 사항을 효율적으로 실현하는 방법은 무엇입니까? Apr 19, 2025 pm 11:36 PM

Redis 캐싱 솔루션은 제품 순위 목록의 요구 사항을 어떻게 인식합니까? 개발 과정에서 우리는 종종 a ... 표시와 같은 순위의 요구 사항을 처리해야합니다.

CentOS7에 Redis를 설치하는 방법 7 CentOS7에 Redis를 설치하는 방법 7 Apr 14, 2025 pm 08:21 PM

공식 Redis 소스에서 소스 코드 패키지를 다운로드하여 최신 버전을 보장하고 개인화 된 방식으로 사용자 정의 할 수 있도록 컴파일하고 설치하십시오. 특정 단계는 다음과 같습니다. 소프트웨어 패키지 목록을 업데이트하고 Redis 디렉토리 생성 Redis 소스 코드 패키지 다운로드 소스 코드 패키지를 압축하고 설치 구성을 컴파일하고 Redis 구성을 수정하여 시작 상태를 확인하십시오.

Docker에 오프라인 미러를 설치하는 방법 Docker에 오프라인 미러를 설치하는 방법 Apr 15, 2025 am 11:36 AM

Docker 이미지를 오프라인으로 설치하려면 다음 단계가 필요합니다. 1. Mirror Tar 파일을 얻으십시오. 2. 미러 파일 내보내기; 3. 미러 파일을 전송하십시오. 4. 미러 파일을 가져옵니다. 5. 거울 설치를 확인하십시오.

nginx와 apache 사이의 선택 : 필요에 맞는 적합 nginx와 apache 사이의 선택 : 필요에 맞는 적합 Apr 15, 2025 am 12:04 AM

Nginx와 Apache는 고유 한 장점과 단점이 있으며 다른 시나리오에 적합합니다. 1.NGINX는 높은 동시성 및 낮은 자원 소비 시나리오에 적합합니다. 2. Apache는 복잡한 구성 및 풍부한 모듈이 필요한 시나리오에 적합합니다. 핵심 기능, 성능 차이 및 모범 사례를 비교하면 요구에 가장 적합한 서버 소프트웨어를 선택할 수 있습니다.

See all articles