文章目錄
- Nginx安裝
- 行程模型
- Nginx web請求處理機制
- Worker搶占機制
- 傳統服務器事件處理
- nginx事件處理
- 如何配置nginx事件處理每個worker處理的最大連接數量及其他配置
- nginx.conf配置
- 配置結構
- 核心組態檔介紹
- nginx.pid打開失敗以及解決辦法
- nginx常用命令決議
- nginx日志切割
- 使用nginx為靜態資源提供服務
- 使用gzip壓縮
- location匹配規則
- DNS(Domain Name System)域名決議
- 使用SwitchHosts模擬本地域名決議
- Nginx解決跨域問題
- 什么是跨域
- springboot解決跨域
- nginx配置跨域
- 在Nginx中實作防盜鏈
- Nginx模塊化體系
- 請求處理
- 負載均衡
- nginx負載均衡決議
- 四層負載均衡
- 七層負載均衡
- DNS地域負載均衡
- 七層負載均衡和四層負載均衡的區別
- nginx負載均衡小實體(一拖三, 1個nginx,3個tomcat)
Nginx安裝
- 下載nginx

-
安裝依賴環境
- 安裝gcc環境
yum install -y gcc-c++ - 安裝PCRE庫,用于決議正則運算式
yum install -y pcre pcre-devel - 安裝zlib壓縮和解壓縮依賴
yum install -y zlib zlib-devel - SSL安全的加密的套接字協議層,用于http安全傳輸,也就是https
yum install -y openssl openssl-devel
- 安裝gcc環境
-
解壓原始碼
tar -zxvf nginx-1.16.1.tar.gz -
創建臨時目錄
mkdir -p /var/temp/nginx -
在nginx原始碼根目錄下,輸入如下命名,構建makefile檔案
./configure \ --prefix=/usr/local/nginx \ --pid-path=/var/run/nginx/nginx.pid \ --lock-path=/var/lock/nginx.lock \ --error-log-path=/var/log/nginx/error.log \ --http-log-path=/var/log/nginx/access.log \ --with-http_gzip_static_module \ --http-client-body-temp-path=/var/temp/nginx/client \ --http-proxy-temp-path=/var/temp/nginx/proxy \ --http-fastcgi-temp-path=/var/temp/nginx/fastcgi \ --http-uwsgi-temp-path=/var/temp/nginx/uwsgi \ --http-scgi-temp-path=/var/temp/nginx/scgi

-
make編譯
make -
安裝
make install -
cd /usr/local/nginx -
啟動 nginx
./sbin/nginx
注意事項,
1.需要開放默認埠80 -
設定nginx命令在全域可以使用
ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx然后就可以在任何地方是用nginx命令了
如果想使用systemctl來管理nginx,可以執行以下步驟
1.關閉nginx . nginx -s stop
2.vim /etc/systemd/system/nginx.service
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
PrivateTmp=true
PIDFile=/var/run/nginx/nginx.pid
[Install]
WantedBy=multi-user.target
systemctl daemon-reload- systemctl常用指令
啟動nginx,systemctl start nginx
設定nginx開機自啟動systemctl enable nginx
查看nginx狀態systemctl status nginx
重啟nginxsystemctl restart nginx
行程模型
-
master行程: 主行程
-
worker行程: 作業行程
一般來說master行程和worker行程都是1,可以使用ps -ef | grep nginx來查看

如果需要修改,則可以進入nginx.conf修改:
vim nginx.conf
#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 '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#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's document root
# concurs with nginx'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 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
當修改完后,需要執行nginx -t查看組態檔是否正確,如果正確的話就可以重啟nginx,使組態檔生效了
在master與worker的關系,類似老板跟員工的關系,master是老板,worker是員工,master給worker發送信號,worker負責干活
信號:
- nginx -s stop
- nginx -s quit
- nginx -s reload
- nginx -t
圖示如下:

Nginx web請求處理機制
Worker搶占機制
如下圖所示,如果有一個請求,各個work行程會進行爭鎖,誰搶到是誰的,需要注意Nginx 所有worker行程協同作業的關鍵(共享記憶體).

[accept_mutex的介紹]
當一個新連接到達時,如果激活了accept_mutex,那么多個Worker將以串行方式來處理,其中有一個Worker會被喚醒,其他的Worker繼續保持休眠狀態;如果沒有激活accept_mutex,那么所有的Worker都會被喚醒,不過只有一個Worker能獲取新連接,其它的Worker會重新進入休眠狀態,這就是「驚群問題」
傳統服務器事件處理

BIO,同步阻塞方式
nginx事件處理

每個worker可以處理大量的連接,cpu越強大,worker數量也可設定的更多,默認每個worker并發請求處理數量為1024.
如何配置nginx事件處理每個worker處理的最大連接數量及其他配置
vim nginx.conf
找到event{}
events {
# 默認使用epoll
use epoll;
# 每個worker允許連接的客戶端最大連接數,默認1024,
worker_connections 1024;
}
nginx.conf配置
配置結構

核心組態檔介紹
#worker執行使用的用戶,默認使用nobody ps -ef | grep nginx可以看到執行的用戶
user root;
# 作業行程數量,如果需要修改作業行程數量,則修改這里就好了
worker_processes 1;
#nginx的6中日志級別(從左到右,級別越來越高) debug info notice warn error crit
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#nginx行程號保存位置
pid logs/nginx.pid;
#
events {
# 默認使用epoll,如果服務器是linux則使用默認就好了
use epoll;
#每個worker允許連接的客戶端最大連接數
worker_connections 1024;
}
#http相關網路傳輸指令塊
http {
# 匯入mime.types 資料傳輸型別指令塊,提高可讀性
include mime.types;
# 默認type型別
default_type application/octet-stream;
#配置日志格式 $ nginx自帶的引數和屬性
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#
#access_log logs/access.log main;
#檔案高效傳輸
sendfile on;
# 和sendfile配套使用,當資料包累計到一定大小再發送
#tcp_nopush on;
#客戶端連接服務器超時時間配置,單位:秒
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip壓縮開關
#gzip on;
#代表是一個虛擬主機,可以把組態檔寫入conf.d檔案夾中,一個服務對應一個組態檔,使用include匯入
include conf.d/*.conf
server {
#監聽的埠號
listen 80;
#監聽的域名
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
#路由,/ 根目錄
location / {
root html;
index index.html index.htm;
}
# error_page 錯誤匹配重定向到錯誤頁面
#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's document root
# concurs with nginx'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 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
nginx.pid打開失敗以及解決辦法

解決辦法:
- mkdir /var/run/nginx -p 創建檔案夾
- nginx -c /usr/local/nginx/config/nginx.conf 重新指定組態檔
- 重啟nginx
nginx常用命令決議
- nginx -s stop 快速停止nginx(暴力關閉)
- nginx -s quit 優雅的停止nginx,會等待任務結束才關閉,只針對http請求
- nginx -t 校驗組態檔是否正確
- nginx -v 查看nginx版本
- nginx -V 展示nginx的具體資訊
- nginx -h 或 nginx -? nginx幫助
- nginx -c <filepath> 指定核心組態檔
nginx日志切割
- 創建可執行檔案
cut_nginx_log.sh內容為:
#!/bin/bash
# nginx日志檔案地址
LOG_PATH="/var/log/nginx/"
# 這里演示為了按分鐘切割
RECORD_TIME=$(date -d "yesterday" + %Y-%m-%d+%H:%M)
#nginx.pid檔案路徑
PID=/var/run/nginx/nginx.pid
# 把當前的access.log重命名
mv ${LOG_PATH}/access.log ${LOG_PATH}/access.${RECORD_TIME}.log
# 把當前的error.log重命名
mv ${LOG_PATH}/error.log ${LOG_PATH}/error.${RECORD_TIME}.log
# 向nginx主行程發送資訊,用于重新打開日志
kill -USR1 `cat $PID`
- 為
cut_nginx_log.sh賦予可執行權限
chmod +x ./cut_nginx_log.sh
- 設定定時任務,切割日志(因為是測驗,所以我們測驗的是分鐘級的,在生產環境中一般是按天切割)
-
安裝定時任務
yum install -y crontabs -
crontab -e編輯并添加一行新的任務:(注意替換腳本路徑)*/1 * * * * /usr/local/nginx/sbin/cut_nginx_log.sh
-
重啟定時任務
service crond restart
-
-
附:定時任務常用命令
- service crond start // 啟動服務
- service crond stop // 關閉服務
- service crond restart // 重啟服務
- service crond reload // 重新載入配置
- crontab -e //編輯任務
- crontab -l //查看任務串列
-
定時任務運算式
Cron運算式,分為5或6個域,每個域代表一個含義,如下所示
分 時 日 月 星期幾 年(可選) 取值范圍 0-59 0-23 1-31 1-12 1-7 -
常用運算式
- 每分鐘執行
*/1 * * * * - 每天凌晨執行(每天晚上23:59):
59 23 * * * - 每天凌晨1點執行:
0 1 * * *
- 每分鐘執行
-
參考檔案
- 每天定時為資料庫備份
使用nginx為靜態資源提供服務
- 在conf.d檔案夾中新建 static.conf,我在/home/resource檔案夾中上傳了一個檔案夾,里面有圖片
server {
listen 1998;
server_name localhost;
location / {
# 資源根路徑
root /home/resource;
# 設定主頁
index index.html;
}
}
-
重啟nginx
nginx -s restart,然后通過服務器ip:1998/imgs/檔案名 訪問檔案,如果無法訪問檢查下防火墻或安全組- firewall防火墻常用命令
- firewall-cmd --list-ports 查看開放的所有埠
- firewall-cmd --permanent --zone=public --add-port=1998/tcp(要開放的埠) 永久開放1998埠
- firewall-cmd --permanent --zone=public --remove-port=1998/tcp 移除1998埠
- systemctl status firewalld 查看防火墻狀態
- systemctl [start,restart, stop] firewalld 開啟|重啟|關閉防火墻
- firewall-cmd --reload 重繪防火墻配置
- firewall防火墻常用命令
-
其實在conf組態檔中,一個server中可以包含多個location進行路徑匹配
location / {
# 資源根路徑
root /home/resource;
# 設定主頁
index index.html;
}
# 別名形式訪問
location /static {
alias /home/resource;
}
使用gzip壓縮
-
修改nginx.conf 開啟gzip為on
gzip on; -
設定gzip
# 限制最小壓縮,小于一個位元組的檔案就不會壓縮了 gzip_min_length 1; # 設定壓縮比,范圍1-9,值越大,壓縮比越大,對cpu壓力也更大 gzip_comp_level 3; # 設定壓縮的檔案型別 gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png application/json;
location匹配規則
location是一種路徑匹配規則
- 默認匹配規則
location /location / { root html; index index.html; } - 精確匹配
# 精確匹配 /home/resource/imgs/face1.png location = /resource/imgs/face1.png { root /home; index index.html; } - 正則運算式
# *代表不區分大小寫 從home檔案夾下一層一層匹配 location ~* \.(GIF|PNG|BMP|JPG|JPEG) { root /home; } # 區分大小寫的精準正則匹配 從home檔案夾下一層一層匹配 location ~ \.(GIF|PNG|BMP|JPG|JPEG) { root /home; } - 以某個字符路徑開頭請求 ^~
# *代表不區分大小寫 從home檔案夾下一層一層匹配 從/home/resource/imgs/開始匹配 location ^~ /resource/imgs { root /home; }
DNS(Domain Name System)域名決議

使用SwitchHosts模擬本地域名決議
- linux 修改hosts檔案
vim /etc/hosts - window修改hosts檔案夾
C:\windows\System32\drivers\etc\hosts
使用switchHosts來簡化hosts修改配置
下載地址:switchHosts
SwitchHosts 除了可以幫助你快速切換不同的 hosts 設定、編輯 hosts 檔案外,它還有著一些很不錯的特性,比如:
- 免費、開源、支持三大作業系統
- 系統托盤快速「一鍵切換」不同的 hosts 方案
- 支持 hosts 檔案語法高亮,可以方便用戶更直觀地閱讀和修改 Hosts 內容;
- 編輯 hosts 時,可以點擊行號可以對行進行快速注釋或取消注釋
- 支持遠程 hosts,直接從指定網址讀取 hosts 內容,方便多臺機器同步 hosts 設定,這是一個很贊的特性!
- 支持 hosts 配置的匯入、匯出備份
- macOS 系統下可以支持 Alfred workflow 快速切換
基本上,有了 SwitchHosts,你就可以對 hosts 為所欲為了,輕松一鍵切換毫無鴨梨,而且,遠程 hsots 方案也可以非常方便經常換電腦使用的人,配置一次到處使用!這一點也是它的亮點,
不過值得注意的是,由于 SwitchHosts 修改 hosts 檔案是屬于修改系統檔案的行為,比如macOS 和 Linux系統需要輸入開機密碼,Windows系統下某些安全軟體可能會提示“有風險”,有問題的話試試將 SwitchHosts 加入排除串列或者信任串列里即可,
Hosts修改后不生效怎么辦?
不過值得注意的是,由于 SwitchHosts 修改 hosts 檔案是屬于修改系統檔案的行為,比如macOS 和 Linux系統需要輸入開機密碼,Windows系統下某些安全軟體可能會提示“有風險”,有問題的話試試將 SwitchHosts 加入排除串列或者信任串列里即可,
怎么情除dns快取?
- 在 Windows 下命令列執行:ipconfig /flushdns
- 在 macOS 下執行命令:sudo killall -HUP mDNSResponder
- 如果你使用 Chrome 瀏覽器,那么可以訪問:chrome://net-internals/#dns,然后點擊「Clear host cache」按鈕來清空瀏覽器里的 DNS 快取,
如果這樣還不生效,那么只能再試試重啟電腦了,一般都OK了,要這樣還是不行,可能就是你的 hosts 寫錯了,
Nginx解決跨域問題
什么是跨域


springboot解決跨域
-
配置攔截器
@Configuration public class CorsConfig { public CorsConfig(){} @Bean public CorsFilter corsFilter(){ CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); // 設定是否可以發送cookie config.setAllowCredentials(true); config.addAllowedMethod("*"); config.addAllowedHeader("*"); UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource(); corsSource.registerCorsConfiguration("/**", config); return new CorsFilter(corsSource); } } -
在controller上使用@CrossOrigin注解
nginx配置跨域
# 允許跨域請求的域,*代表所有
add_header 'Access-Control-Allow-Origin' *;
# 允許帶上cookie請求
add_header 'Access-Control-Allow-Credentials' 'true';
# 允許的請求方法, *表示所有方法
add_header 'Access-Control-Allow-Method' *;
# 允許所有請求的頭
add_header 'Access-Control-Allow-Headers' *;
示例:
server {
listen 1998;
server_name localhost;
# 允許跨域請求的域,*代表所有
add_header 'Access-Control-Allow-Origin' *;
# 允許帶上cookie請求
add_header 'Access-Control-Allow-Credentials' 'true';
# 允許的請求方法, *表示所有方法
add_header 'Access-Control-Allow-Method' *;
# 允許所有請求的頭
add_header 'Access-Control-Allow-Headers' *;
location / {
# 資源根路徑
root /home/resource;
# 設定主頁
index index.html;
}
}
在Nginx中實作防盜鏈
server {
listen 1998;
server_name localhost;
# 允許跨域請求的域,*代表所有
add_header 'Access-Control-Allow-Origin' *;
# 允許帶上cookie請求
add_header 'Access-Control-Allow-Credentials' 'true';
# 允許的請求方法, *表示所有方法
add_header 'Access-Control-Allow-Method' *;
# 允許所有請求的頭
add_header 'Access-Control-Allow-Headers' *;
# 對源站點校驗,是否是test.com下的站點
valid_referers *.test.com;
# 非法引入會進入下方的判斷
if ($invalid_referer){
return 404;
}
location / {
# 資源根路徑
root /home/resource;
# 設定主頁
index index.html;
}
}
Nginx模塊化體系

nginx core實作了底層的通訊協議,為其他模塊和Nginx行程構建了基本的運行時環境,并且構建了其他各模塊的協作基礎,
http模塊和mail模塊位于nginx core和各功能模塊的中間層,這2個模塊在nginx core之上實作了另外一層抽象,分別處理與http協議和email相關協議(SMTP/IMAP/POP3)有關的事件,并且確保這些事件能被以正確的順序呼叫其它的一些功能模塊,
(1) event module:搭建了獨立于作業系統的事件處理機制的框架,以及提供了各具體事件的處理,包括ngx_event_module、ngx_event_core_module和ngx_epoll_module等,Nginx具體使用何種事件處理模塊,這依賴于具體的作業系統和編譯選項,
(2) phase handler:此型別的模塊也被直接稱為handler模塊,主要負責處理客戶端請求并產生待回應內容,比如ngx_http_module模塊,負責客戶端的靜態頁面請求處理并將對應的磁盤檔案準備為回應內容輸出,
(3) output filter:也稱為filter模塊,主要是負責對輸出的內容進行處理,可以對輸出進行修改,比如可以實現對輸出的所有html頁面增加預定義的footbar一類的作業,或者對輸出的圖片的URL進行替換之類的作業,
(4) upstream:實作反向代理功能,將真正的請求轉發到后端服務器上,并從后端服務器上讀取回應,發回客戶端,upstream模塊是一種特殊的handler,只不過回應內容不是真正由自己產生的,而是從后端服務器上讀取的,
(5) load-balancer:負載均衡模塊,實作特定的演算法,在眾多的后端服務器中,選擇一個服務器出來作為某個請求的轉發服務器,
(6) extend module:根據特定業務需要撰寫的第三方模塊,
請求處理
下面將會以http請求處理為例來說明請求、配置和模塊是如何串起來的,
當Nginx讀取到一個HTTP Request的header時,首先查找與這個請求關聯的虛擬主機的配置,如果找到了則這個請求會經歷以下幾個階段的處理(phase handlers):
NGX_HTTP_POST_READ_PHASE: 讀取請求內容階段
NGX_HTTP_SERVER_REWRITE_PHASE: Server請求地址重寫階段
NGX_HTTP_FIND_CONFIG_PHASE:配置查找階段
NGX_HTTP_REWRITE_PHASE:Location請求地址重寫階段
NGX_HTTP_POST_REWRITE_PHASE:請求地址重寫提交階段
NGX_HTTP_PREACCESS_PHASE: 訪問權限檢查準備階段
NGX_HTTP_ACCESS_PHASE: 訪問權限檢查階段
NGX_HTTP_POST_ACCESS_PHASE: 訪問權限檢查提交階段
NGX_HTTP_TRY_FILES_PHASE: 內容產生階段
NGX_HTTP_LOG_PHASE:日志模塊處理階段
在內容產生階段,為了給一個request產生正確的response,Nginx必須把這個請求交給一個合適的content handler去處理,如果這個request對應的location在組態檔中被明確指定了一個content handler,那么Nginx就可以通過對location的匹配,直接找到這個對應的handler,并把這request交給這個content handler去處理,這樣的配置指令包括perl、flv、proxy_pass、mp4等,
如果一個request對應的location并沒有直接配置的content handler,那么Nginx依次作如下嘗試:
(1) 如果一個location里面有配置random_index on,那么隨即選擇一個檔案發送給客戶端,
(2) 如果一個location里面有配置index指令,那么發送index指令指定的檔案給客戶端,
(3) 如果一個location里面有配置autoindex on,那么就發送請求地址對應的服務端路徑下的檔案串列給客戶端,
(4) 如果這個request對應的location上有設定gzip_static on,那么就查找是否有對應的.gz檔案存在,如果有的話,就發送這個客戶端(客戶端支持gzip的情況下).
(5) 請求的URI如果對應的一個靜態檔案,static module就發送靜態檔案的內容到客戶端,
內容產生階段完成以后,生成的輸出會被傳遞到filter模塊去進行處理,filter模塊也是與location相關的,所有的filter模塊都被組織成了一條鏈,輸出會依次穿越所有的filter,直到有一個filter模塊的回傳值表明已經處理完成, 接下來就可以發送response給客戶端了,
負載均衡
nginx負載均衡決議
什么是負載均衡:Load balancing,即負載均衡,是一種計算機技術,用來在多個計算機(計算機集群)、網路連接、CPU、磁盤驅動器或其他資源中分配負載,以達到最優化資源使用、最大化吞吐率、最小化回應時間、同時避免過載的目的,
為什么需要負載均衡:

負載均衡(Load Balance),意思是將負載(作業任務,訪問請求)進行平衡、分攤到多個操作單元(服務器,組件)上進行執行,是解決高性能,單點故障(高可用),擴展性(水平伸縮)的終極解決方案,
更多關于負載均衡的資料
四層負載均衡
基于IP+埠的負載均衡
也就是主要通過報文中的目標地址和埠,再加上負載均衡設備設定的服務器選擇方式,決定最終選擇的內部服務器,
常見的四層負載均衡實作軟體:
F5:硬體負載均衡器,功能很好,但是成本很高,
lvs:重量級的四層負載軟體
nginx:輕量級的四層負載軟體,帶快取功能,正則運算式較靈活,1.9版本后支持
haproxy:模擬四層轉發,較靈活
七層負載均衡
從第七層"應用層"開始, 根據虛擬的url或IP,主機名接收請求,再轉向相應的處理服務器,
在四層負載均衡的基礎上(沒有四層是絕對不可能有七層的),再考慮應用層的特征,比如同一個Web服務器的負載均衡,除了根據VIP加80埠辨別是否需要處理的流量,還可根據七層的URL、瀏覽器類別、語言來決定是否要進行負載均衡,舉個例子,如果你的Web服務器分成兩組,一組是中文語言的,一組是英文語言的,那么七層負載均衡就可以當用戶來訪問你的域名時,自動辨別用戶語言,然后選擇對應的語言服務器組進行負載均衡處理,
對應的負載均衡器稱為七層交換機(L7 switch),除了支持四層負載均衡以外,還有分析應用層的資訊,如HTTP協議URI或Cookie資訊,實作七層負載均衡,此種負載均衡器能理解應用協議,
實作七層負載均衡的軟體有:
haproxy:天生負載均衡技能,全面支持七層代理,會話保持,標記,路徑轉移;
nginx:只在http協議和mail協議上功能比較好,性能與haproxy差不多;
apache:功能較差
Mysql proxy:功能尚可,
總的來說,一般是lvs做4層負載;nginx做7層負載(也能做4層負載, 通過stream模塊);haproxy比較靈活,4層和7層負載均衡都能做
DNS地域負載均衡
所謂DNS地域是基于地理的負載均衡 例子: 北方的用戶訪問北京的機房, 南方的用戶訪問深圳的機房,DNS負載均衡的本質是DNS決議同一個域名可以訪問不同的IP地址 例如: 同樣是www.baidu.com,北京用戶決議后獲取的地址是61.135.165.224(北京機房IP),南方用戶決議后獲取的地址是14.215.177.38(深圳機房IP)
DNS負載均衡實作簡單,成本低,但也存在粒度太粗、負載均衡演算法少等缺點,
優點
1. 簡單、成本低: 負載均衡作業交給DNS服務器處理,無須自己開發或者維護負載均衡設備
2. 就近訪問,提升訪問速度: DNS決議時可以根據請求來源IP 決議成距離用戶最近的服務器地址,可以加快訪問速度,改善性能,
缺點
1. 更新不及時:DNS快取帶時間比較長,修改DNS配置厚,由于快取的原因,還有有很多用戶會繼續訪問修改前的IP,這樣帶訪問會失敗, 達不到負載均衡帶目的,并且也會影響用戶正常的使用
2. 擴展性差: DNS負載均衡的控制權在域名商那里,無法根據業務特點針對其做更多的定制化功能和擴展特性
3. 分配策略比較簡單:DNS負載均衡支持帶演算法少, 不能區分服務器的差異(無法根據系統與服務狀態來判斷負載),也無法感知后端服務器帶狀態,
七層負載均衡和四層負載均衡的區別
四層負載均衡只是對請求進行轉發,七層負載均衡可以對請求進行處理,然后再轉發,
四層負載均衡就像銀行的自助排號機,每一個達到銀行的客戶根據排號機的順序,選擇對應的視窗接受服務;而七層負載均衡像銀行大堂經理,先確認客戶需要辦理的業務,再安排排號,這樣辦理理財、存取款等業務的客戶,會根據銀行內部資源得到統一協調處理,加快客戶業務辦理流程,
nginx負載均衡小實體(一拖三, 1個nginx,3個tomcat)
nginx服務器和3個tomcat服務器需要可以通信
圖示

具體實作:
1.服務器資訊
nginx: 192.168.65.100
tomcat1: 192.168.65.101
tomcat2: 192.168.65.102
tomcat3: 192.168.65.103
2.啟動3臺tomcat服務器
3.配置nginx服務器, 在conf.d中新建tomcatGroup.conf
# 配置上游服務器
upstram tomcats {
server 192.168.65.101:8080;
server 192.168.65.102:8080;
server 192.168.65.103:8080;
}
server{
listen 80;
server_name localhost;
location / {
proxy_pass http://tomcats;
}
}
4.重啟nginx服務 nginx -s restart
進入瀏覽器訪問:192.168.65.100查看結果
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/256680.html
標籤:其他
下一篇:冪塔個位數的計算(歐拉降冪板子)
