上一篇文章 <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