本文作為ASP.Net Core Web API學習的一部分,介紹了如何使用Nginx進行簡單的負載配置。
1、將ASP.Net Core Web API項目發布到不同的服務器
例如,將項目發布到本地不同的文件夾中。
2、使用dotnet命令啟動已發布的ASP.Net Core Web API服務
-> dotnet WebApi.dll --urls="http://*:3001" --ip="127.0.0.1" --port=3001
-> dotnet WebApi.dll --urls="http://*:3002" --ip="127.0.0.1" --port=3002
-> dotnet WebApi.dll --urls="http://*:3003" --ip="127.0.0.1" --port=3003
3、安裝Nginx
在http://nginx.org/en/download.html下載安裝Nginx穩定版,這里安裝的版本是1.18.0。
4、設置Nginx
Nginx配置文件路徑為nginx-1.18.0\conf\nginx.conf。
(1) 配置端口
Nginx啟動不了時,可能就是因為端口被占用了,因此可以手動設置Nginx的端口。
端口位置為nginx.conf -> http -> server -> listen,默認為80端口,可以修改為需要設置的端口。
(2) 配置基於轉發服務器
server_name localhost;
server_name指令可以設置基於域名的虛擬主機,根據請求頭部的內容,一個ip的服務器可以配置多個域名,多個域名之間以空格分開。
(3) 設置代理路徑
location / {
#root html;
#index index.html index.htm;
proxy_pass http://webApi; #設置代理轉發,轉發到服務器列表
}
(4) 設置服務器列表
upstream webApi {
server localhost:3001;
server localhost:3002;
server localhost:3003;
}
5、測試Nginx服務器
假如api接口路徑為http://localhost:3001/api/weatherforecast,在瀏覽器中輸入http://localhost:80/api/ weatherforecast,則依次會調用3001、3002、3003端口所在服務器接口,對所有接口輪詢調用。
Nginx默認使用輪詢策略轉發請求到服務器列表,也可以設置權重等策略。