問題: 前端發送的請求,是如何請求到后端服務器的?
如,前端請求地址:http://loclhost/api/employee/login:
后端相應請求地址:http://loclhost:8080/admin/employee/login
回答: 使用nginx進行反向代理,即將前端發送的動態請求由nginx轉發到后端服務器。
nginx代理的好處:
使用nginx進行反向代理的好處:
-
提高訪問速度:nginx可以緩存數據,當請求同樣的接口地址時,無需請求真正的后端服務,直接將nginx中緩存的數據響應給前端,從而提高了響應速度。
-
進行負載均衡:系統上線之后,有可能訪問壓力較大,后端可能需要部署多臺服務器構成服務器集群。此時,nginx可以作為負載均衡器,將前端發過來的大量請求均衡的分配給后端的各個服務器,如下圖所示:
-
保證后端服務安全:在真實企業項目當中,很多后端服務并沒有直接暴露給互聯網,而是部署在公司內部的局域網內的,并不是對外開放的,因此通過前端并不能直接請求到后端的服務的,所以需要將前端請求發送到nginx服務器,然后nginx服務器走內網發送到后端服務器,如下圖所示:
如何實現相關nginx配置:
負載均衡策略:
舉例
user root;
worker_processes 1;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;#gzip on;map $http_upgrade $connection_upgrade{default upgrade;'' close;}upstream webservers{server 127.0.0.1:8080 weight=90 ;#server 127.0.0.1:8088 weight=10 ;}server {listen 80;server_name localhost;location / {root /home/zxy/Projects/CangQiong/FrontEnd/nginx-1.20.2/html/sky;index index.html index.htm;}# redirect server error pages to the static page /50x.html#error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}# 反向代理,處理管理端發送的請求location /api/ {proxy_pass http://localhost:8080/admin/;#proxy_pass http://webservers/admin/;}# 反向代理,處理用戶端發送的請求location /user/ {proxy_pass http://webservers/user/;}}
}