2024-06-20
后端技术
00
请注意,本文编写于 91 天前,最后修改于 90 天前,其中某些信息可能已经过时。

目录

1、Windows 安装 Consul
2、新建三个 WebAPI

环境:
VS2022
Docker
Ocelot.Provider.Consul 17.0.1

1、Windows 安装 Consul

官网
将下载好的压缩包放到某个文件夹下,cd 定位到这个目录,运行

csharp
# Development consul agent -dev -ui -node=cy

2、新建三个 WebAPI

csharp
dotnet new webapi -n Gateways -f net5(网关1) dotnet new webapi -n App.Gateways -f net5(网关2) dotnet new webapi -n App.ApiAggregator -f net5 dotnet new sln dotnet sln add .\Gateways dotnet sln add .\App.Gateways dotnet sln add .\App.ApiAggregator # Gateways 和 App.Gateways 添加包 Ocelot.Provider.Consul # 修改启动端口 Gateways:6001 App.Gateways:6002 App.ApiAggregator:6004

GatewaysApp.Gateways 集成 Ocelot

csharp
# ConfigureServices services.AddOcelot(Configuration).AddConsul(); # 在 Configure 方法最后面加入 app.UseOcelot().Wait();

Gateways 加入 Ocelot.json 文件,并修改属性为 如果较新则复制

json
{ "GlobalConfiguration": { "RequestIdKey": "OcRequestId", "AdministrationPath": "/administration" }, "Routes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 6004 } ], "UpstreamPathTemplate": "/mobileAgg/api/{everything}", "UpstreamHttpMethod": [] }, { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 6002 } ], "UpstreamPathTemplate": "/mobile/api/{everything}", "UpstreamHttpMethod": [] } ] }

JSON 文件复制一份到 App.Gateways ,并修改属性为 如果较新则复制,修改 60026001
GatewaysApp.GatewaysProgram 文件加入

csharp
.ConfigureAppConfiguration(builder => { builder.AddJsonFile("ocelot.json", false, true); })

在三个API项目中新建 ConsulExtensions 类,三个文件中的 port 分别对应启动端口,在 ConfigureService 方法中加入

csharp
services.UseConsul();

注意:ConsulClient 中的地址如果为本地开发环境,需为localhost,ip地址也一样

csharp
public static class ConsulExtension { public static void UseConsul(this IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); var client = new ConsulClient(m => { m.Address = new Uri("http://localhost:8500"); m.Datacenter = "dc1"; }); string ip = "localhost"; int port = 6001; client.Agent.ServiceRegister(new AgentServiceRegistration { ID = "Gateway", Name = "Gateway", Port = port, Address = ip, Check = new AgentServiceCheck { Interval = TimeSpan.FromSeconds(5), HTTP = $"http://{ip}:{port}/api/Health", Timeout = TimeSpan.FromSeconds(5), DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5) } }); Console.WriteLine($"http://{ip}:{port}/api/Health"); } }

在三个API项目中新建控制器 HealthController,用于健康检查,三个控制器分别返回 6001-Gateways6002-Gateways6004-App.ApiAggregator

csharp
[Route("api/[controller]")] [ApiController] public class HealthController : ControllerBase { [HttpGet] public IActionResult Get() { Console.WriteLine("Gateways"); return Ok("6001-Gateways"); } }

image.png localhost:8500 访问 Consul dashboard,同一端口通过不同请求头访问不同API接口,如图:

image.png

本文作者:一叶知秋

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!