上一篇文章 <C# HttpClient 使用 Consul 發現服務> 解決了內部服務之間的調用問題, 對外提供網關服務尚未解決, 最後我選擇了 nginx-upsync-module 做爲服務發現和轉發的工具,html
如今 .net core 已經有不少包含權鑑、熔斷的網關工具了, nginx-upsync-module 只提供了服務發現(支持Consul, 不須要重啓nginx)與轉發的功能, 功能少性能強, 若是不滿意 ocelot 的性能, 能夠試一試.linux
一個WebApi最好只提供一個服務, 因此在這個示例中, 我準備了兩個項目 SayHelloService 和 WeatherForecastService, 這兩個服務均會註冊到consul;nginx
nginx 經過 nginx-upsync-module 發現提供 WeatherForecastService 的實例c++
WeatherForecastService 經過 ConsulDiscovery 發現提供 SayHelloService 的實例git
因此 nginx 收到請求後轉發到 WeatherForecastService, WeatherForecastService 再調用 SayHelloServicegithub
0. 環境json
CentOS Linux release 7.7.1908 (Core) IP地址: 192.168.0.51 , 測試階段建議關閉防火牆和SELinuxbootstrap
consul_1.7.2_linux_amd64.zip(自行下載)app
nginx-1.17.10.tar.gz(自行下載)工具
nginx-upsync-module-master.zip (示例代碼中 或 https://github.com/weibocom/nginx-upsync-module )
示例代碼 (連接)
開發機: .net core 3.1, IP地址192.168.0.3
推薦使用 MobaXterm 做爲 Linux 的SSH工具, 能夠很方便的上傳文件
1. 編譯nginx
爲簡單起見, 能夠直接 進入su模式
將nginx-1.17.10.tar.gz 和 nginx-upsync-module-master.zip 上傳到 /usr/local/src (哈哈, 這裏多半會遇到權限問題), 而後解壓
tar -zxvf nginx-1.17.10.tar.gz unzip nginx-upsync-module-master.zip
編譯
yum -y install gcc gcc-c++ automake zlib zlib-devel openssl openssl--devel pcre pcre-devel cd nginx-1.17.10/ ./configure --add-module=../nginx-upsync-module-master make && make install
nginx 就編譯到 /usr/local/nginx 了
3. 運行consul
mkdir /usr/local/consul
將 consul 執行程序上傳到 /usr/local/consul
chmod +x consul ./consul agent -server -data-dir=data -bind=192.168.0.51 -client=0.0.0.0 -bootstrap-expect 1 -ui
4. 配置nginx.conf
vi /usr/local/nginx/conf/nginx.conf
#user nobody; worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; keepalive_timeout 65; upstream weatherforecast{ server 127.0.0.1:11111; ## nginx 要求必須有這一行 ## 鏈接consul server 獲取動態 upstream 配置負載均很信息 間隔0.5秒獲取consul配置信息 upsync 127.0.0.1:8500/v1/catalog/service/WeatherForecastService upsync_timeout=6m upsync_interval=500ms upsync_type=consul_services strong_dependency=off; ## 拉取的服務列表保存起來, 這樣的話, 即便consul失效了, 也可暫用這些信息 upsync_dump_path /tmp/weatherforecast_consul.conf; } server { listen 80; server_name localhost; location / { proxy_pass http://weatherforecast; index index.html index.htm; } } }
啓動nginx
cd /usr/local/nginx/sbin
./nginx
5. 準備 SayHelloService 和 WeatherForecastService
代碼就不在這裏展現了, 直接到 github 下載, 而後使用 "發佈" 生成程序, 而後上傳呢到 Linux
須要注意的是
A. 由於是nginx做爲網關對外提供服務, SayHelloService 和 WeatherForecastService 只須要綁定 127.0.0.1 便可
B. 默認SayHelloService 的 appsettings.json 指明瞭 ServiceIP=127.0.0.1, ServicePort=5000
WeatherForecastService的 appsettings.json 指明瞭 ServiceIP=127.0.0.1, ServicePort=5002
啓動的時候綁定的urls 要與其一致
cd /home/zhouke/SayHelloService dotnet SayHelloService.dll --urls="http://localhost:5000"
cd /home/zhouke/WeatherForecastService dotnet WeatherForecastService.dll --urls="http://localhost:5002"
End