Linux下使用Nginx+多Tomcat实现负载均衡及Session共享

搭建环境

  1. 腾讯云服务器内存型M2,2 核 16 GB 200 Mbps 高性能云硬盘,操作系统CentOS7.4 64位;
  2. 一键Java环境安装脚本,网址:https://oneinstack.com/

负载均衡操作步骤

1.Java环境安装

这里使用的OneinStack一键安装环境,参考网址:https://oneinstack.com/auto/,选择如下图所示:

 

登录云服务器,粘贴复制的安装命令:

wget -c http://mirrors.linuxeye.com/oneinstack-full.tar.gz && tar xzf oneinstack-full.tar.gz && ./oneinstack/install.sh --nginx_option 1 --tomcat_option 3 --jdk_option 3 --reboot 

运行命令。我的云服务器是200M的弹性宽带,入门环境安装时间较长,这边要耐心等待一下。

出现如下图所示,表示安装成功。

浏览器访问云服务器ip,显示如下:

2.多Tomcat配置

首先,把tomcat服务停了:

/usr/local/tomcat/bin/shutdown.sh

为了便于区分,这边重命名原来的tomcat:

 mv /usr/local/tomcat /usr/local/tomcat1

复制tomcat2:

cp -r /usr/local/tomcat1 /usr/local/tomcat2

 在/data/wwwroot 下新建两个工程目录:

cd /data/wwwroot
mkdir webapp1
mkdir webapp2

新建JavaWeb项目NginxDemo,打成war包,FTP上传到webapp1。首页内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tomcat1 Session Id</title>
</head>
<body>
<h1>Tomcat1</h1>
<h1>Session Id : <%= request.getSession().getId() %></h1>
<h1>Dream Car</h1>
<img alt="" src="./images/bm.jpg" style="width: 800px;">
</body>
</html>

新建JavaWeb项目NginxDemo,打成war包,FTP上传到webapp2。首页内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tomcat2 Session Id</title>
</head>
<body>
<h1>Tomcat2</h1>
<h1>Session Id : <%= request.getSession().getId() %></h1>
<h1>Dream Car</h1>
<img alt="" src="./images/bm.jpg" style="width: 800px;">
</body>
</html>

配置tomcat1:

cd /usr/local/tomcat1/conf
vi server.xml

 

 修改server.xml 如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE server-xml [
<!ENTITY vhost-localhost SYSTEM "file:///usr/local/tomcat1/conf/vhost/localhost.xml">
]>
<Server port="8001" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
  <Listener className="org.apache.catalina.core.AprLifecycleListener"/>
<!--
  <Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener" rmiRegistryPortPlatform="8081" rmiServerPortPlatform="8082" />
-->
  <GlobalNamingResources>
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <Service name="Catalina">
    <Connector port="8081"
              protocol="org.apache.coyote.http11.Http11AprProtocol"
              connectionTimeout="20000"
              redirectPort="8443"
              maxThreads="1000"
              minSpareThreads="20"
              acceptCount="1000"
              maxHttpHeaderSize="65536"
              disableUploadTimeout="true"
              useBodyEncodingForURI="true"
              enableLookups="false"
              URIEncoding="UTF-8" />
    <Engine name="Catalina" defaultHost="localhost">
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>
      &vhost-localhost;
    </Engine>
  </Service>
</Server>

具体修改内容如下图所示:

修改/usr/local/tomcat1/conf/vhost/localhost.xml文件,内容如下:

<Host name="localhost" appBase="/data/wwwroot/webapp1" unpackWARs="true" autoDeploy="true">
  <Context path="" docBase="/data/wwwroot/webapp1/NginxDemo" reloadable="false" crossContext="true"/>
  <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
    prefix="localhost_access_log" suffix=".txt" pattern="%h %l %u %t &quot;%r&quot; %s %b" />
  <Valve className="org.apache.catalina.valves.RemoteIpValve" remoteIpHeader="X-Forwarded-For"
    protocolHeader="X-Forwarded-Proto" protocolHeaderHttpsValue="https"/>
</Host>

 同理,修改/usr/local/tomcat2/conf/server.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE server-xml [
<!ENTITY vhost-localhost SYSTEM "file:///usr/local/tomcat2/conf/vhost/localhost.xml">
]>
<Server port="8002" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
  <Listener className="org.apache.catalina.core.AprLifecycleListener"/>
<!--
  <Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener" rmiRegistryPortPlatform="8081" rmiServerPortPlatform="8082" />
-->
  <GlobalNamingResources>
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <Service name="Catalina">
    <Connector port="8082"
              protocol="org.apache.coyote.http11.Http11AprProtocol"
              connectionTimeout="20000"
              redirectPort="8443"
              maxThreads="1000"
              minSpareThreads="20"
              acceptCount="1000"
              maxHttpHeaderSize="65536"
              disableUploadTimeout="true"
              useBodyEncodingForURI="true"
              enableLookups="false"
              URIEncoding="UTF-8" />
    <Engine name="Catalina" defaultHost="localhost">
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>
      &vhost-localhost;
    </Engine>
  </Service>
</Server>

同理修改/usr/local/tomcat2/conf/vhost/localhost.xml文件,内容如下:

<Host name="localhost" appBase="/data/wwwroot/webapp2" unpackWARs="true" autoDeploy="true">
  <Context path="" docBase="/data/wwwroot/webapp2/NginxDemo" reloadable="false" crossContext="true"/>
  <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
    prefix="localhost_access_log" suffix=".txt" pattern="%h %l %u %t &quot;%r&quot; %s %b" />
  <Valve className="org.apache.catalina.valves.RemoteIpValve" remoteIpHeader="X-Forwarded-For"
    protocolHeader="X-Forwarded-Proto" protocolHeaderHttpsValue="https"/>
</Host>

3.nginx配置

修改nginx.conf配置文件:

cd /usr/local/nginx/conf
vi nginx.conf
user www www;
worker_processes auto;

error_log /data/wwwlogs/error_nginx.log crit;
pid /var/run/nginx.pid;
worker_rlimit_nofile 51200;

events {
  use epoll;
  worker_connections 51200;
  multi_accept on;
}

http {
  include mime.types;
  default_type application/octet-stream;
  server_names_hash_bucket_size 128;
  client_header_buffer_size 32k;
  large_client_header_buffers 4 32k;
  client_max_body_size 1024m;
  client_body_buffer_size 10m;
  sendfile on;
  tcp_nopush on;
  keepalive_timeout 120;
  server_tokens off;
  tcp_nodelay on;

  fastcgi_connect_timeout 300;
  fastcgi_send_timeout 300;
  fastcgi_read_timeout 300;
  fastcgi_buffer_size 64k;
  fastcgi_buffers 4 64k;
  fastcgi_busy_buffers_size 128k;
  fastcgi_temp_file_write_size 128k;
  fastcgi_intercept_errors on;

  #Gzip Compression
  gzip on;
  gzip_buffers 16 8k;
  gzip_comp_level 6;
  gzip_http_version 1.1;
  gzip_min_length 256;
  gzip_proxied any;
  gzip_vary on;
  gzip_types
    text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml
    text/javascript application/javascript application/x-javascript
    text/x-json application/json application/x-web-app-manifest+json
    text/css text/plain text/x-component
    font/opentype application/x-font-ttf application/vnd.ms-fontobject
    image/x-icon;
  gzip_disable "MSIE [1-6]\.(?!.*SV1)";

  ##Brotli Compression
  #brotli on;
  #brotli_comp_level 6;
  #brotli_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;

  ##If you have a lot of static files to serve through Nginx then caching of the files' metadata (not the actual files' contents) can save some latency.
  #open_file_cache max=1000 inactive=20s;
  #open_file_cache_valid 30s;
  #open_file_cache_min_uses 2;
  #open_file_cache_errors on;

######################## default ############################
  upstream webapps {
    server 127.0.0.1:8081;
    server 127.0.0.1:8082;
  }
  server {
    listen 80;
    server_name _;
    access_log /data/wwwlogs/access_nginx.log combined;
    root /data/wwwroot;
    index index.html index.htm index.jsp;
    #error_page 404 /404.html;
    #error_page 502 /502.html;
    location /nginx_status {
      stub_status on;
      access_log off;
      allow 127.0.0.1;
      deny all;
    }
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
      proxy_pass http://webapps;
      expires 30d;
      access_log off;
    }
    location ~ .*\.(js|css)?$ {
      proxy_pass http://webapps;
      expires 7d;
      access_log off;
    }
    location ~ {
      proxy_pass http://webapps;
      include proxy.conf;
    }
    location ~ ^/(\.user.ini|\.ht|\.git|\.svn|\.project|LICENSE|README.md) {
      deny all;
    }
  }
########################## vhost #############################
  include vhost/*.conf;
}

修改内容如下图所示:

重启nginx:

service nginx restart

启动两个tomcat:

/usr/local/tomcat1/bin/startup.sh
/usr/local/tomcat2/bin/startup.sh

打开浏览器,访问云服务器ip,页面刷新时出现如下图所示:

Session共享配置 

停止tomcat服务

/usr/local/tomcat1/bin/shutdown.sh
/usr/local/tomcat2/bin/shutdown.sh

修改tomcat1/conf/server.xml,找到<Engine name="Catalina" defaultHost="localhost">,下面加入如下配置:

<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" />

同样,tomcat2/conf/server.xml也加上。

修改webapp1、webapp2 下面的JavaWeb项目:web.xml文件,加上如下配置:

<distributable/>

操作完成后,启动两个Tomcat:

/usr/local/tomcat1/bin/startup.sh
/usr/local/tomcat2/bin/startup.sh

刷新浏览器,如下:

JVM监控工具:

1.jps(JVM Process Status Tools)

-q只输出LVMID
-m输出JVM启动时传给主类的方法
-l输出主类的全名,如果是Jar则输出jar的路径
-v输出JVM的启动参数

2.jstack(JVM Stack Trace for java) 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值