1. 程式人生 > 其它 >nginx實現反向代理與動靜分離

nginx實現反向代理與動靜分離

1 安裝兩個slaver

1.1 伺服器配置

java37master:1G
java37slaver1:512M
java37slaver2:512M

1.2 建立虛擬機器

  • 設定記憶體為512M

  • 設定網路

  • 設定主機名稱並應用:java37slaver1+java37slaver2

  • 設定編碼集

  • 設定張號密碼

  • 注意:如果出現錯誤:法獲得VMCI驅動程式的版本:控制代碼無效

    https://blog.51cto.com/xuan97916/1909845
    

1.3 新增基本的配置

  • 安裝ifconfig
* 檢視ifconifg是否存在:ll /sbin/ifconfig   不存在
* 安裝ifconfig: yum install ifconifg      缺少包
* 檢視依賴的包:  yum search ifconifg       缺少net-tools.x86_64
* 安裝依賴的包:  yum install net-tools.x86_64 -y
  • 安裝vim
 yum -y install vim*
  • 安裝rz
yum install lrzsz -y

1.4 安裝jdk

  • 安裝環境gc++
* yum install glibc.i686 -y
* yum -y install libaio.so.1 libgcc_s.so.1 libstdc++.so.6
# 如果第二步出錯:執行一下命令:yum install --setopt=protected_multilib=false libgcc
* yum update libstdc++-4.4.7-4.el6.x86_64
* yum install gcc-c++	-y
  • 建立資料夾
mkdir -p /usr/soft
  • 把jdk的壓縮檔案上傳到/usr/soft下
  • 壓縮
  • 重新命名為java11
  • 配置環境變數
vim /etc/profile
# 配置jdk11
export JAVA_HOME=/usr/soft/jdk11
#  export JRE_HOME=$JAVA_HOME/jre  #jdk11沒有jre 不要配置
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export PATH=$PATH:$JAVA_HOME/bin
  • 載入配置檔案
source /etc/profile
  • 驗證
java
javac
java -version

1.5 安裝tomcat

  • 上傳tomcat的壓縮檔案到/usr/soft下
  • 解壓
  • 重新命名為tomcat9
  • 關閉防火牆
[root@java37master tomcat9]# systemctl stop firewalld.service #關閉防火牆
[root@java37master tomcat9]# firewall-cmd --state   #檢視防火牆狀態
[root@java37master tomcat9]# systemctl status firewalld.service   #檢視防火牆狀態
[root@java37master tomcat9]# systemctl disable firewalld.service #關閉開機啟動防火牆
  • 進入bin包啟動tomcat
./startup.sh
  • 瀏覽器訪問tomcat

1.6 兩個slaver上面釋出專案

  • 資料庫使用master上的即可

  • 把war複製到slaver1和slaver2的webapps下

  • 開啟tomcat

  • 瀏覽器訪問即可

2 配置靜態ip(三臺都做)

2.1 檢視三臺伺服器的名稱

  • 應該不需要修改:安裝虛擬機器時已經指定
[root@java37master ~]# cat  /etc/hostname
java37master
[root@java37slaver1 ~]# cat  /etc/hostname
java37slaver1
[root@java37slaver2 ~]# cat  /etc/hostname
java37slaver2
  • 如果修改 需要重啟虛擬機器
reboot

2.2獲取主機的閘道器(Gateway)

DNS域名系統(英文:Domain Name System,縮寫:DNS)是網際網路的一項服務。它作為將域名和IP地址相互對映的一個分散式資料庫,能夠使人更方便地訪問網際網路
[root@java37slaver2 ~]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.56.2    0.0.0.0         UG    100    0        0 ens33
192.168.56.0    0.0.0.0         255.255.255.0   U     100    0        0 ens33

2.3 設定每臺主機的靜態ip

[root@java37slaver2 ~]# vim /etc/sysconfig/network-scripts/ifcfg-ens33
[root@java37slaver2 ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE="Ethernet"
PROXY_METHOD="none"
BROWSER_ONLY="no"
BOOTPROTO="static" #配置靜態ip::1 設定為static
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
IPV6_ADDR_GEN_MODE="stable-privacy"
NAME="ens33"
UUID="d0371869-480f-4966-b578-f4c19877545a"
DEVICE="ens33"
ONBOOT="yes"

#配置靜態ip::2 新增以下五項
# 新增下面五項  配置靜態ip
IPADDR=192.168.56.130   #當前主機ip  #每臺主機的ip不同:
NETMASK=255.255.255.0
GATEWAY=192.168.56.2   #閘道器
DNS1=8.8.8.8   
DNS2=114.114.114.114
  • 重啟網路
systemctl restart network

3 設定三臺伺服器的dns(三臺都做)

3.1 概念

三臺伺服器之間 通過主機名即可訪問對方

3.2 編輯/etc/hosts::

[root@java37slaver2 ~]# vim /etc/hosts
[root@java37slaver2 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

#配置三臺伺服器的dns
192.168.56.128 java37master
192.168.56.129 java37slaver1
192.168.56.130 java37slaver2

3.3 ping測試是否可以通訊

[root@java37slaver2 ~]# ping java37slaver2
[root@java37slaver2 ~]# ping java37slaver1
[root@java37slaver2 ~]# ping java37master1
PING java37slaver2 (192.168.56.130) 56(84) bytes of data.
64 bytes from java37slaver2 (192.168.56.130): icmp_seq=1 ttl=64 time=0.135 ms
64 bytes from java37slaver2 (192.168.56.130): icmp_seq=2 ttl=64 time=0.038 ms
64 bytes from java37slaver2 (192.168.56.130): icmp_seq=3 ttl=64 time=0.036 ms
64 bytes from java37slaver2 (192.168.56.130): icmp_seq=4 ttl=64 time=0.059 ms
...
^C
--- java37slaver2 ping statistics ---
19 packets transmitted, 19 received, 0% packet loss, time 18027ms
rtt min/avg/max/mdev = 0.032/0.056/0.135/0.029 ms

4 ssh免密登入

SSH 為 [Secure Shell]的縮寫,由 IETF 的網路小組(Network Working Group)所制定;SSH 為建立在應用層基礎上的安全協議。SSH 是較可靠,專為[遠端登入]會話和其他網路服務提供安全性的協議。利用 SSH 協議可以有效防止遠端管理過程中的資訊洩露問題。 
目的:在一個連結中在三臺伺服器之間來回切換

4.1 生成公鑰和祕鑰(三臺伺服器都做)

  • ssh-keygen
[root@java37slaver2 ~]# ssh-keygen  #生成公鑰和祕鑰
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:rg+D53FfFk6WXKuVR1oW1lAYWT3Q03zwnecCl5VZRp0 root@java37slaver2
The key's randomart image is:
+---[RSA 2048]----+
|             .*&^|
|              +E@|
|            . +.@|
|           . = O.|
|        S   * * o|
|     . .   + + o |
|    . = o   =    |
|     o * . o     |
|      o.. .      |
+----[SHA256]-----+
# 其間看提示 點選enter鍵  或者輸入yes

4.2 把公鑰和祕鑰發給master(三臺都做)

  • ssh-copy-id java37master
[root@java37slaver2 ~]# ssh-copy-id java37master
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host 'java37master (192.168.56.128)' can't be established.
ECDSA key fingerprint is SHA256:nbd7BL+4vc6QScOYqafO9p7KkxDkPb+On1BEOSRgdpc.
ECDSA key fingerprint is MD5:01:22:0b:dc:39:de:ac:6e:8a:c8:a4:00:09:71:e9:3b.
Are you sure you want to continue connecting (yes/no)? yes   #輸入yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@java37master's password:   #輸入密碼

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'java37master'"
and check to make sure that only the key(s) you wanted were added.

4.3 檢視master上的檔案/root/.ssh/authorized_keys

[root@java37master ~]# cat /root/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDHwdT7gfnM1szAO3iEbtwIv2UicU99N+oqHYSHoEuz8O+4QL1WRYmal1UoeF6AKTeO2FFJR60+mRfIH3orl8euLyh0cVkl4P9lN+SYoRFhnX2qfs5OmN/3p/GRt1g6EZCTGn/JPBAbCn3ueQefABq09DnduMYaFo5x5+Bc/KilRgdF6Eb7n4ha/WoZP530FdLUi1oAHMX4sobu2hHj7//ciptdFPje6VxMRPXHx2kdddL4FqxsYH1WlSZhuNC0ZlXZ7raV5dWwIxeSjw8293PRXuq3dkGRUF9VYD74onyN/U4msIBQ5ZNEf9l+28Hp6R65MJWSAirXWIoT3JEnS65n root@java37slaver2
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC/HW7pqOk4lSVbO36hn59k9FCa+I2iWc0D6Zb5VtPLxEqvyVXpd+bVLrDdqLyPimET3P4p9AsDQ+dp5EGaBQMNOyjlD0SHfFHvhF8GR+XPa9w7K6mnuniQZq1bylt0Kh4bXVaLAsyvIKUJLiMnElb0L2bFmuO6gBzze1JPAJ+aEwUBcxPVI+wr1M9IMMfOWknBf3dzLY3CBni+e9g+YacsimgGG6A6lFveuF5Wb19Z2mEn+Ep7Qt108FJoTIjxqzfCNlRChA1o4fdJx52sIHT8xtFT8uuQo2UekSScdVVROE1mrJj/Bco28K/cXyyQu3D5dIsLclN/Dthw61weiK47 root@java37slaver1
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC1zZxKdO/kYyOFBQJdkSADm6oMQXxQxxCHQXUitaPB3ckD0XI9awkUvuzUuaGr2ApHpaAXd6gZGBexbsWfWBBwZB6lRDzJZEajEblp5KGvcHJdDLzG1sMNfs4oxFOh0Gf2NeG0to/tbFnMOZ/hHUyy6KQv9BmPzIH6gEaMoNYxms/mr0NzEIVNNtXp9dke89x4nNkHsILXMKDhkvbXAjIieX9p2zCZEhTWrwuFS+AabnewjV3lCEAxxVQ4OlPTnWjdHlEmAtLq2ZiHL7YGPpSjdBqDINE9ams1EZZcQY+Qv2cZgmAeyXo1LePEtH/2XcqEUnbYEkSGRNhLQgiBm4QN root@java37master

4.4 把master上的此檔案發給兩個slaver(只在master上做)

  • scp 本地檔案 遠端登入使用者名稱@遠端主機:遠端主機的目錄
[root@java37master ~]# scp /root/.ssh/authorized_keys  root@java37slaver1:/root/.ssh
The authenticity of host 'java37slaver1 (192.168.56.129)' can't be established.
ECDSA key fingerprint is SHA256:S8/WIYoiYeX3yEKdkcW7blvb6VvY5K7HLdIgKgvE4FI.
ECDSA key fingerprint is MD5:62:6b:14:c3:14:cb:de:8c:a9:2b:6a:07:88:dd:07:18.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'java37slaver1,192.168.56.129' (ECDSA) to the list of known hosts.
root@java37slaver1's password: 
authorized_keys                                                                       100% 1199     1.0MB/s   00:00    
[root@java37master ~]# scp /root/.ssh/authorized_keys  root@java37slaver2:/root/.ssh
The authenticity of host 'java37slaver2 (192.168.56.130)' can't be established.
ECDSA key fingerprint is SHA256:YVz8ctecowRD4iP5833WxJRi1gd4O4vm1piMKh5Xrls.
ECDSA key fingerprint is MD5:93:96:8e:81:79:43:92:13:46:86:6b:53:31:80:58:5b.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'java37slaver2,192.168.56.130' (ECDSA) to the list of known hosts.
root@java37slaver2's password: 
authorized_keys                                                                       100% 1199   930.5KB/s   00:00 

4.5 通過ssh實現三臺伺服器的免密登入(三臺都做)

  • 測試9次
[root@java37master ~]# ssh java37master
[root@java37master ~]# ssh java37slaver1
[root@java37master ~]# ssh java37slaver2
  • 退出當前賬戶:exit
[root@java37master ~]# exit
登出
Connection to java37master closed.

5 三臺伺服器都發布專案

  • 使用master的mysql
  • 把專案打包為war包
  • 把war包放入/tomcat9/webapps下
  • 啟動三臺伺服器的tomcat
  • 監控tomcat的日誌輸出資訊:tail -f xxx
  • 通過瀏覽器訪問:

1 nginx

1.1 概念

Nginx (engine x) 是一個高效能的HTTP和反向代理web伺服器,同時也提供了IMAP/POP3/SMTP服務。
Nginx是由伊戈爾·賽索耶夫為俄羅斯訪問量第二的Rambler.ru站點(俄文:Рамблер)開發的,第一個公開版本0.1.0釋出於2004年10月4日。
因它的穩定性、豐富的功能集、簡單的配置檔案和低系統資源的消耗而聞名

1.2 安裝:只在master上安裝

http://nginx.org/en/download.html
  • 安裝nginx的依賴
[root@java37master ~]# yum install yum-utils
...
  • 建立yum的配置資訊
[root@java37master ~]# touch /etc/yum.repos.d/nginx.repo #建立yum配置檔案
[root@java37master ~]# vim /etc/yum.repos.d/nginx.repo 
[root@java37master ~]# cat /etc/yum.repos.d/nginx.repo  #新增如下程式碼  指定下載stable版本
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
  • 安裝nginx
[root@java37master ~]# yum install nginx  -y

1.3 關閉linux自帶防毒軟體selinux

  • 檢視selinux的狀態
[root@java37master ~]# getenforce
Enforcing  #處於防禦狀態
  • 修改配置檔案 取消開機啟動
[root@java37master ~]# vim /etc/selinux/config
[root@java37master ~]# cat /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled #取消開機啟動
# SELINUXTYPE= can take one of three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected. 
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted 
  • 重啟master
reboot

1.4 啟動並測試ngixn

[root@java37master ~]# systemctl start nginx    #開啟nginx
[root@java37master ~]# systemctl restart nginx  #重啟nginx
[root@java37master ~]# systemctl stop nginx     #關閉nginx
[root@java37master ~]# systemctl status nginx   #檢視nginx狀態
  • 通過瀏覽器訪問nginx:nginx的預設埠和http一樣 都是80埠

2 nginx實現反向代理

2.1 概念

通過nginx給伺服器叢集的多臺伺服器 提供一個統一的訪問入口

2.2 實現其功能::只在master上執行

  • 建立檔案:
[root@java37master conf.d]# touch /etc/nginx/conf.d/cloud37.conf
  • 編輯檔案:指定url的解析規則
[root@java37master conf.d]# vim  /etc/nginx/conf.d/cloud37.conf
[root@java37master conf.d]# cat /etc/nginx/conf.d/cloud37.conf
#為三臺伺服器對應的叢集 起個名字
upstream cloudserver
{
  server 192.168.56.128:8080;
  server 192.168.56.129:8080;
  server 192.168.56.130:8080;
}
#提供server配置 實現反向代理url轉換規則
server
{
  #指定nginx監聽的埠
  listen  80;
  #指定nginx的主機的ip地址 master的ip
  server_name  192.168.56.128;
  #指定url的轉換規則
  location  /cloud37{
      proxy_pass  http://cloudserver/java37_08_cloud;
  }
  #瀏覽器請求:http://192.168.56.128:80/cloud37 時 會被nginx解析為
  #http://192.168.56.128:8080/java37_08_cloud
  #http://192.168.56.129:8080/java37_08_cloud
  #http://192.168.56.130:8080/java37_08_cloud
}
  • 重啟ngixn
[root@java37master conf.d]# systemctl restart nginx.service
  • 對專案進行修改:所有請求都更改為http://192.168.56.128:80/cloud37
<!-- 主要是三個地方需要改進:1 所有style和script標籤-->
<!-- 主要是三個地方需要改進:2 所有ajax的url-->
<!-- 主要是三個地方需要改進:3 img的src-->
<html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt"  uri="http://java.sun.com/jsp/jstl/fmt"%>
<head>
        <!--#新增  定義一個pagescore域屬性 記錄nginx的地址-->
        <c:set  var="path" value="http://192.168.56.128:80/cloud37"/>
        <title>雲盤專案</title>
        <!--1.1 引入min.css-->
        <link type="text/css" rel="stylesheet" href="${pageScope.path}/bootstrap-3.3.7-dist/css/bootstrap.min.css"/>
        <!--1.2 引入bootstrap-theme.min.css-->
        <link type="text/css" rel="stylesheet" href="${pageScope.path}/bootstrap-3.3.7-dist/css/bootstrap-theme.min.css"/>

        <!--2.1 引入bootstrap-table.min.css-->
        <link type="text/css" rel="stylesheet" href="${pageScope.path}/bootstrap-3.3.7-dist/css/bootstrap-table.min.css"/>

        <!-- 3.1 bootstarp-editable基本使用:1引入bootstrap-editable.css -->
        <link type="text/css" rel="stylesheet" href="${pageScope.path}/bootstrap-3.3.7-dist/css/bootstrap-editable.css" />

        <!--1.3 引入jquery-->
        <script type="text/javascript" src="${pageScope.path}/js/jquery-3.3.1.min.js"></script>
        <!--1.4 引入bootstrap.min.js-->
        <script type="text/javascript" src="${pageScope.path}/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

        <!--2.2 引入bootstrap-table.min.js-->
        <script type="text/javascript" src="${pageScope.path}/bootstrap-3.3.7-dist/js/bootstrap-table.min.js"></script>
        <!--2.3 引入bootstrap-table-editable.min.js-->
        <script type="text/javascript" src="${pageScope.path}/bootstrap-3.3.7-dist/js/bootstrap-table-editable.min.js"></script>
        <!--2.4 引入bootstrap-table-zh-CN.min.js-->
        <script type="text/javascript" src="${pageScope.path}/bootstrap-3.3.7-dist/js/bootstrap-table-zh-CN.min.js"></script>

        <!--3.1 引入jquery.serializejson.min.js 使用serializeJSON方法-->
        <script type="text/javascript" src="${pageScope.path}/js/jquery.serializejson.min.js"></script>

        <!--3.3 bootstarp-editable基本使用:2引入bootstrap-editable.min.js -->
        <script type="text/javascript"
                src="${pageScope.path}/bootstrap-3.3.7-dist/js/bootstrap-editable.min.js"></script>
</head>

<body>
        <!--0:定義全域性變數-->
        <script type="text/javascript">
            var uid;
            var dfu="0";
            var path="${pageScope.path}/"; //更改path的寫法 不要出現核心標籤庫
        </script>
 
        <!--登入模態框:類似於彈出框-->
        <div class="modal fade" id="userLoginModal" >
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                           ...
                            <div class="form-group">
                                <label class="control-label">驗&nbsp;證&nbsp;碼:</label>
                                <img src="${pageScope.path}/user/yzmImg.action"  id="img_yzm" />
                                <input type="text" class="form-control"  name="uyzm" value="1234">
                            </div>
                        </form>
                    </div>
                         ...
                </div>
            </div>
        </div>
        <script type="text/javascript">
                 .....
                //更改驗證碼
                $("#img_yzm").bind("click",function(){
                     $("#img_yzm").attr("src","${pageScope.path}/user/yzmImg.action?n="+Math.random());
                });
            });
        </script>
</body>
</html>
  • 專案clean package
  • 把三臺伺服器的tomcat關閉 清除/webapps下的java37*
  • 把打好的war新增到webapps下
  • 開啟tomcat
  • 開啟日誌監控
  • 通過瀏覽器訪問:http://nginxip:nginxport/cloud37/index.jsp
注意:請求的時候一定要加資源名稱

3 nginx實現負載均衡

3.1 概念

負載均衡:負載均衡也是 Nginx常用的一個功能,當一臺伺服器的單位時間內的訪問量越大時,伺服器壓力就越大,大到超過自身承受能力時,伺服器就會崩潰。為了避免伺服器崩潰,讓使用者有更好的體驗,我們通過負載均衡的方式來分擔伺服器壓力。
我們可以建立很多很多伺服器,組成一個伺服器叢集,當用戶訪問網站時,先訪問一箇中間伺服器,在讓這個中間伺服器在伺服器叢集中選擇一個壓力較小的伺服器,然後將該訪問請求引入該伺服器。
如此以來,使用者的每次訪問,都會保證伺服器叢集中的每個伺服器壓力趨於平衡,分擔了伺服器壓力,避免了伺服器崩潰的情況。
負載均衡配置一般都需要同時配置反向代理,通過反向代理跳轉到負載均衡。
nginx 根據伺服器的效能 按制定策略來合理分配處理請求的比例

3.2 方式

更改nginx的配置檔案:/etc/nginx/conf.d/cloud37.conf 的cloudserver資訊

3.3 負載均衡策略

1 輪訓

預設策略:
所有伺服器按順序輪流處理請求
適合於伺服器效能相同的叢集
upstream cloudserver
{
  #預設輪訓
  server 192.168.56.128:8080;
  server 192.168.56.129:8080;
  server 192.168.56.130:8080;
}

2 權重

根據伺服器效能 設定處理請求的比例
適合於伺服器效能差別大的叢集
upstream cloudserver
{
   #1輪訓  預設
   #2權重
   #  #weight:指定比例
   #    #fail_timeout:指定最大等待時間
  server 192.168.56.128:8080 weight=1 fail_timeout=10s;
  server 192.168.56.129:8080 weight=1 fail_timeout=10s;
  server 192.168.56.130:8080 weight=4 fail_timeout=10s;
}
  • 注意 重啟nginx
systemctl restart nginx

3 ip_hash

每臺伺服器設定個編號:從0開啟
客戶端ip的hashcode值%伺服器臺數 =n  :讓編號為n的伺服器處理此請求
特點:同一個客戶端的所有請求都只被伺服器處理
upstream cloudserver
{
   #1輪訓  預設
   #2權重
   #  #weight:指定比例
   #    #fail_timeout:指定最大等待時間
   #server 192.168.56.128:8080 weight=1 fail_timeout=10s;
   #server 192.168.56.129:8080 weight=1 fail_timeout=10s;
   #server 192.168.56.130:8080 weight=4 fail_timeout=10s;
   
   #3ip_hash
   ip_hash;
   server 192.168.56.128:8080 fail_timeout=10s;
   server 192.168.56.129:8080 fail_timeout=10s;
    server 192.168.56.130:8080 fail_timeout=10s;
}

4 fair

nginx接受到請求 會詢問整個伺服器叢集  把請求交給第一個響應的伺服器
upstream cloudserver
{
  server 192.168.254.128:8080;
  server 192.168.254.129:8080;
  server 192.168.254.130:8080; 
  fair;
}
# fair測試出錯::::需要新增外掛:::新增外掛失敗!yum安裝沒有對應的配置檔案
#unknown directive "fair" in /etc/nginx/conf.d/cloud37.conf:23
#nginx的錯誤日誌位置:/var/log/nginx/error.log

5 url_hash

nginx根據請求的url的hashcode%伺服器個數=n 把請求交給編號為n的伺服器
upstream cloudserver
{
   #1輪訓  預設
   #2權重
   #  #weight:指定比例
   #    #fail_timeout:指定最大等待時間
   #server 192.168.56.128:8080 weight=1 fail_timeout=10s;
   #server 192.168.56.129:8080 weight=1 fail_timeout=10s;
   #server 192.168.56.130:8080 weight=4 fail_timeout=10s;
   
   #3ip_hash
   #ip_hash;
   #server 192.168.56.128:8080 fail_timeout=10s;
   #server 192.168.56.129:8080 fail_timeout=10s;
   #server 192.168.56.130:8080 fail_timeout=10s;
   #
   
   #4 fair
   #server 192.168.56.128:8080;
   #server 192.168.56.129:8080;
   #server 192.168.56.130:8080;
   #fair;
   #
   
   #5 url_hash
   server 192.168.56.128:8080 fail_timeout=10s;
   server 192.168.56.129:8080 fail_timeout=10s;
   server 192.168.56.130:8080 fail_timeout=10s;
   hash $request_uri;
}

4 動靜分離

4.1 概念

靜態資源(html/css/js/img) 不需要依賴web應用伺服器的解析  直接放在nginx上 訪問時直接響應給客戶端
提高響應效率 降低伺服器壓力

4.2 對專案進行修改

1 把jsp轉化為html
2 把style和script的路徑都更改為相對路徑
3 把<c:set 刪除
4 直接給path賦值:var path = "http://192.168.56.128:80/cloud37/";
5 去除所有的${}
  $(function () {
        //var user = "${sessionScope.user}";
        //alert(user);
        //if (user) {
        //    uid = "${sessionScope.user.uid}";
        //    setTableData();
        //} else {
            $("#userLoginModal").modal("show");//彈出登入模態框
        //}
    });
6 更改img的連線
    <div class="form-group">
                        <label class="control-label">驗&nbsp;證&nbsp;碼:</label>
                        <img src="user/yzmImg.action" id="img_yzm"/>
                        <input type="text" class="form-control" name="uyzm" value="1234">
    </div>
    
    ...
    //更改驗證碼
    $("#img_yzm").bind("click", function () {
         $("#img_yzm").attr("src", "user/yzmImg.action?n=" + Math.random());
    });

4.3 把所有靜態資源存入一個資料夾cloud37中

4.4 把專案中這些靜態資源刪除

4.5 啟動tomcat

  • 專案clean package
  • 關閉三個tomcat
  • 清除webapps下的java37*
  • 把war重新上傳到webapps下
  • 開啟三臺伺服器

4.6 把靜態資原始檔夾cloud37上傳到/usr/share/nginx資料夾下

[root@java37master bin]# cd /usr/share/nginx
[root@java37master nginx]# ll
總用量 0
drwxr-xr-x  6 root root 102 12月 22 17:52 cloud37
drwxr-xr-x. 2 root root  40 12月 22 11:06 html

4.7 更改nginx的配置檔案 並重啟

[root@java37master conf.d]# pwd
/etc/nginx/conf.d
[root@java37master conf.d]# vim cloud37.conf  #更改配置檔案
[root@java37master conf.d]# systemctl restart nginx.service #重啟nginx
[root@java37master conf.d]# cat cloud37.conf 
#為三臺伺服器對應的叢集 起個名字
upstream cloudserver
{
   #1輪訓  預設
   #2權重
   #  #weight:指定比例
   #    #fail_timeout:指定最大等待時間
   #server 192.168.56.128:8080 weight=1 fail_timeout=10s;
   #server 192.168.56.129:8080 weight=1 fail_timeout=10s;
   #server 192.168.56.130:8080 weight=4 fail_timeout=10s;
   
   #3ip_hash
   #ip_hash;
   #server 192.168.56.128:8080 fail_timeout=10s;
   #server 192.168.56.129:8080 fail_timeout=10s;
   #server 192.168.56.130:8080 fail_timeout=10s;
   #
   
   #4 fair
   #server 192.168.56.128:8080;
   #server 192.168.56.129:8080;
   #server 192.168.56.130:8080;
   #fair;
   #
   
   #5 url_hash
   server 192.168.56.128:8080 fail_timeout=10s;
   server 192.168.56.129:8080 fail_timeout=10s;
   server 192.168.56.130:8080 fail_timeout=10s;
   hash $request_uri;
}
#提供server配置 實現反向代理url轉換規則
server
{
  #指定nginx監聽的埠
  listen  80;
  #指定nginx的主機的ip地址 master的ip
  server_name  192.168.56.128;

   #動靜分離
  location ~ .*\.(html|css|js|eot|svg|ttf|woff|woff2)$
  {
           root  /usr/share/nginx;
  }

  #指定url的轉換規則
  location  /cloud37{
      proxy_pass  http://cloudserver/java37_08_cloud;
  }
  #瀏覽器請求:http://192.168.56.128:80/cloud37 時 會被nginx解析為
  #http://192.168.56.128:8080/java37_08_cloud
  #http://192.168.56.129:8080/java37_08_cloud
  #http://192.168.56.130:8080/java37_08_cloud
}

4.8 瀏覽器訪問:靜態資源index.html