1.前言
已經掌握了spring cloud 得使用 ,但這是在內部網絡做業務 ,現在需要 在外部網絡 訪問內部網絡 服務 ,引入了 服務端負載均衡 Nginx ,
Nginx 根據預定的策略 ,將請求路由給 Zuul網關集群中得一個 ,然后由 Zuul網關過濾后路由到指定的 微服務,業務處理完后,處理結果返回zuul網關 ,然后再返回給Nginx服務器再返回前端。
為了簡便演示具體操作,忽略zuul部分 ,使用兩個微服務做集群即可
2.提前准備兩個spring boot工程做集群
端口分別是8001 ,8003 ,地址都是localhost 【127.0.0.1】具體配置這里不講解,可看我得其他隨筆由詳細記錄
8001端口 controller層
package com.example.provider8001.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class PRController { @RequestMapping(value = "/getname",method = RequestMethod.GET) public String getname(String name){ System.out.println("接收名字="+name); return "我是端口8001,你大爺叫:"+name; } }
8003端口 controller層
package com.example.providerredis8003.controller; import com.example.providerredis8003.service.EatService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController public class FoodController { @RequestMapping(value = "/getname",method = RequestMethod.GET) public String getname(String name){ System.out.println("接收名字="+name); return "我是端口8003,你三爺叫:"+name; } }
3.配置Nginx的配置文件 nginx.conf
直接打開修改文件
默認的未修改過的文件

#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; # } #} }
完整詳細的配置【有點亂,這是我的筆記】

#配置用戶或者組,默認為nobody nobody。 #user nobody; #允許生成的進程數,默認為1 worker_processes 1; #pid /nginx/pid/nginx.pid; #指定nginx進程運行文件存放地址 #制定日志路徑,級別。這個設置可以放入全局塊,http塊,server塊, #級別以此為:debug|info|notice|warn|error|crit|alert|emerg #error_log log/error.log debug; #其他得如這樣寫 #error_log logs/error.log notice; #error_log logs/error.log info; # #events塊:配置影響nginx服務器或與用戶的網絡連接。有每個進程的最大連接數, #選取哪種事件驅動模型處理連接請求,是否允許同時接受多個網路連接,開啟多個網絡連接序列化等。 events { #設置網路連接序列化,防止驚群現象發生,默認為on #accept_mutex on; #設置一個進程是否同時接受多個網絡連接,默認為off #multi_accept on; #事件驅動模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport #use epoll; #最大連接數,默認為512 worker_connections 1024; } #http塊:可以嵌套多個server,配置代理,緩存,日志定義等絕大多數功能和第三方模塊的配置。如文件引入, #mime-type定義,日志自定義,是否使用sendfile傳輸文件,連接超時時間,單連接請求數等。 http { #文件擴展名與文件類型映射表 include mime.types; #默認文件類型,默認為text/plain default_type application/octet-stream; #取消服務日志 #access_log off; #自定義格式 #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #注意:1.$remote_addr 與$http_x_forwarded_for 用以記錄客戶端的ip地址; #2.$remote_user :用來記錄客戶端用戶名稱; #3.$time_local : 用來記錄訪問時間與時區; #4.$request : 用來記錄請求的url與http協議; #5.$status : 用來記錄請求狀態;成功是200, #6.$body_bytes_s ent :記錄發送給客戶端文件主體內容大小;7.$http_refe #7.驚群現象:一個網路連接到來,多個睡眠的進程被同事叫醒,但只有一個進程能獲得鏈接,這樣會影響系統性能。 #8.每個指令必須有分號結束。 #------------------------------------ #combined為日志格式的默認值 #access_log logs/access.log main; #允許sendfile方式傳輸文件,默認為off,可以在http塊,server塊,location塊。 sendfile on; #每個進程每次調用傳輸數量不能大於設定的值,默認為0,即不設上限。 #sendfile_max_chunk 100k; #tcp_nopush on; #連接超時時間,默認為75s,可以在http,server,location塊。 keepalive_timeout 65; #服務器列表 ,集群地址 ,providernames 是名字 ,可自定義 upstream pancm{ server 127.0.0.1:8001; server 127.0.0.1:8003; } #gzip on; #錯誤頁 也可寫在server塊里面 #error_page 404 https://www.baidu.com; #server塊:配置虛擬主機的相關參數,一個http中可以有多個server。 server { #單連接請求上限次數。 keepalive_requests 120; #nginx監聽端口 listen 4001; # Nginx監聽地址,可以使用域名,多個用空格分隔。 server_name localhost; #server_name 127.0.0.1; #添加頭部信息 # proxy_set_header Cookie $http_cookie; # proxy_set_header X-Forwarded-Host $host; # proxy_set_header X-Forwarded-Server $host; # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #通過代理地址關鍵字,重定義路徑 # 訪問 http://localhost:4001/api/getname?name=tom ,4001端口是nginx的 ,相當於直接訪問 http://localhost:8001/getname?name=tom # location /api/ { #這里以spring boot 服務提供者 端口 8001 為例子 # proxy_pass http://localhost:8001/; #注意:使用代理地址時末尾記得加上斜杠"/"。 # } #------------------ #通過alias關鍵字,重定義路徑 #此時,通過瀏覽器訪問http://127.0.0.1:7001/file/t.txt,則訪問服務器的文件是/home/china/areas/t.txt # location /file/ { #這里以spring boot 服務提供者 端口 8001 為例子 # alias /home/china/areas/; # } #------------ #alias可以使用正則表達式,如 #location ~ ^/test/(\w+).(\w+)$ { # alise /home/china/$2/$1.$2; #} #訪問/test/t.conf,則實際訪問的是/home/china/conf/t.conf #-------------------------------- #通過root關鍵字,重定義路徑 #此時,通過瀏覽器訪問http://127.0.0.1:7001/test/t.txt,則訪問服務器的文件是/home/china/areas/test/t.txt # location /file/ { #這里以spring boot 服務提供者 端口 8001 為例子 #root /home/china/areas/; #} #------------------ ##location塊:配置請求的路由,以及各種頁面的處理情況。 #根據 pancm 定義的服務器列表進行負載均衡路由 location / { #根目錄,注意:使用"/"攔截全路徑的時候記得放在最后。 # root path; #設置默認頁 #index index.html index.htm; #index表示首頁 #請求轉向 pancm 定義的服務器列表 #代理路徑,一般配置upstream后面的名稱用於實現負載均衡,可以直接配置ip進行跳轉; proxy_pass http://pancm; #拒絕的ip # deny 127.0.0.1; #允許的ip #allow 172.18.5.54; #index表示首頁 index index.html index.htm; } #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; } } }
簡潔版的配置【去除多余的注釋】

#允許生成的進程數,默認為1 worker_processes 1; #events塊:配置影響nginx服務器或與用戶的網絡連接。有每個進程的最大連接數, #選取哪種事件驅動模型處理連接請求,是否允許同時接受多個網路連接,開啟多個網絡連接序列化等。 events { #最大連接數,默認為512 worker_connections 1024; } #http塊:可以嵌套多個server,配置代理,緩存,日志定義等絕大多數功能和第三方模塊的配置。如文件引入, #mime-type定義,日志自定義,是否使用sendfile傳輸文件,連接超時時間,單連接請求數等。 http { #文件擴展名與文件類型映射表 include mime.types; #默認文件類型,默認為text/plain default_type application/octet-stream; #允許sendfile方式傳輸文件,默認為off,可以在http塊,server塊,location塊。 sendfile on; #連接超時時間,默認為75s,可以在http,server,location塊。 keepalive_timeout 65; #服務器列表 ,集群地址 ,providernames 是名字 ,可自定義 upstream pancm{ server 127.0.0.1:8001; server 127.0.0.1:8003; } #server塊:配置虛擬主機的相關參數,一個http中可以有多個server。 server { #單連接請求上限次數。 keepalive_requests 120; #nginx監聽端口 listen 4001; # Nginx監聽地址,可以使用域名,多個用空格分隔。 server_name localhost; #server_name 127.0.0.1; #location塊:配置請求的路由,以及各種頁面的處理情況。 #根據 pancm 定義的服務器列表進行負載均衡路由 location / { #請求轉向 pancm 定義的服務器列表 #代理路徑,一般配置upstream后面的名稱用於實現負載均衡,可以直接配置ip進行跳轉; proxy_pass http://pancm; #index表示首頁 index index.html index.htm; } #錯誤頁 error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
【我這里使用了默認的輪詢負載均衡策略】
1)nginx實現負載均衡有幾種模式:
(1).輪詢:每個請求按時間順序逐一分配到不同的后端服務器,也是nginx的默認模式。輪詢模式的配置很簡單,只需要把服務器列表加入到upstream模塊中即可。
下面的配置是指:負載中有三台服務器,當請求到達時,nginx按照時間順序把請求分配給三台服務器處理。
upstream serverList { server 1.2.3.4; server 1.2.3.5; server 1.2.3.6; }
(2).ip_hash:每個請求按訪問IP的hash結果分配,同一個IP客戶端固定訪問一個后端服務器。可以保證來自同一ip的請求被打到固定的機器上,可以解決session問題。
下面的配置是指:負載中有三台服務器,當請求到達時,nginx優先按照ip_hash的結果進行分配,也就是同一個IP的請求固定在某一台服務器上,其它則按時間順序把請求分配給三台服務器處理。
upstream serverList { ip_hash server 1.2.3.4; server 1.2.3.5; server 1.2.3.6; }
(3).url_hash:按訪問url的hash結果來分配請求,相同的url固定轉發到同一個后端服務器處理。
upstream serverList { server 1.2.3.4; server 1.2.3.5; server 1.2.3.6; hash $request_uri; hash_method crc32; }
(4)fair:按后端服務器的響應時間來分配請求,響應時間短的優先分配。
upstream serverList { server 1.2.3.4; server 1.2.3.5; server 1.2.3.6; fair; }
2)而在每一種模式中,每一台服務器后面的可以攜帶的參數有:
- down: 當前服務器暫不參與負載
- weight: 權重,值越大,服務器的負載量越大。
- max_fails:允許請求失敗的次數,默認為1。
- fail_timeout:max_fails次失敗后暫停的時間。
- backup:備份機, 只有其它所有的非backup機器down或者忙時才會請求backup機器。
如下面的配置是指:負載中有三台服務器,當請求到達時,nginx按時間順序和權重把請求分配給三台服務器處理,例如有100個
請求,有30%是服務器4處理,有50%的請求是服務器5處理,有20%的請求是服務器6處理。
upstream serverList { server 1.2.3.4 weight=30; server 1.2.3.5 weight=50; server 1.2.3.6 weight=20; }
如下面的配置是指:負載中有三台服務器,服務器4的失敗超時時間為60s,服務器5暫不參與負載,服務器6只用作備份機。
upstream serverList { server 1.2.3.4 fail_timeout=60s; server 1.2.3.5 down; server 1.2.3.6 backup; }
配置完成后,保存即可
4.測試
啟動端口8001和8003工程集群 ,
(1)直接訪問端口8001 , http://localhost:8001/getname?name=tom
(2)直接訪問端口8003 , http://localhost:8003/getname?name=tom2
都可以正常訪問
(3)啟動Nginx
怎么查看有沒有啟動呢?
打開cmd 輸入指令 tasklist /fi "imagename eq nginx.exe"
其他命令

Windows下Nginx的啟動、停止等命令 在Windows下使用Nginx,我們需要掌握一些基本的操作命令,比如:啟動、停止Nginx服務,重新載入Nginx等,下面我就進行一些簡單的介紹。 1、啟動: C:\server\nginx-1.0.2>start nginx或 C:\server\nginx-1.0.2>nginx.exe 2、停止: C:\server\nginx-1.0.2>nginx.exe -s stop或 C:\server\nginx-1.0.2>nginx.exe -s quit 注:stop是快速停止nginx,可能並不保存相關信息;quit是完整有序的停止nginx,並保存相關信息。 3、重新載入Nginx: C:\server\nginx-1.0.2>nginx.exe -s reload 當配置信息修改,需要重新載入這些配置時使用此命令。 4、重新打開日志文件: C:\server\nginx-1.0.2>nginx.exe -s reopen 5、查看Nginx版本: C:\server\nginx-1.0.2>nginx -v 詳細介紹請查看全文:https://cnblogs.com/qianzf/ 原文博客的鏈接地址:https://cnblogs.com/qzf/ 查看是否開啟成功 tasklist /fi "imagename eq nginx.exe" 強制關閉服務進程 taskkill /fi "imagename eq nginx.EXE" /f
(4)訪問Nginx端口 4001 ,讓其根據均衡策略路由到集群中的一個
請求第一次 http://localhost:4001/getname?name=tom3
路由成功 ,
請求第二次 http://localhost:4001/getname?name=tom3
成功了
因為使用輪詢策略,所以是在集群里輪流路由
-----------------------
參考博文原址 :
https://www.cnblogs.com/xiangzhong/p/11355414.html
https://www.cnblogs.com/muyun/p/9652379.html
https://blog.csdn.net/liaoxuda_edu/article/details/72870923
https://blog.csdn.net/qq_43732691/article/details/103449054
https://www.cnblogs.com/xuwujing/p/11953697.html