Ocelot是一个用.NET Core实现并且开源的API网关技术,它的功能包括了:路由、请求聚合、服务发现、认证、鉴权、限流熔断、并内置了负载均衡器、Service Fabric、Skywalking等的集成。而且这些功能都只需要简单的配置即可完成。
(1)配置说明
(1)新建Peng.Core.ApiGateWay,Install-Package Ocelot
这里还是使用Apollo远程配置
<ItemGroup> <PackageReference Include="Ocelot" Version="18.0.0" /> <PackageReference Include="Com.Ctrip.Framework.Apollo.Configuration" Version="2.6.2" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" /> </ItemGroup>
(2)注入Ocelot,这里还需要添加Cors
builder.Services.AddOcelot(_configuration); app.UseOcelot().Wait();
(3)配置网关,服务A,服务B启动的IP
(4)配置Apollo
新建一个NameSpace
ocelotconfig.json
{ "GlobalConfiguration": { "BaseUrl": "https://localhost:9000/" }, "Routes": [ { "DownstreamScheme": "https", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": "9001" } ], "UpstreamPathTemplate": "/api/a/v1/{controller}", "DownstreamPathTemplate": "/api/a/v1/{controller}", "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT", "OPTIONS" ], "UseServiceDiscovery": false, "LoadBalancerOptions": { "Type": "RoundRobin" } }, { "DownstreamScheme": "https", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": "9002" } ], "UpstreamPathTemplate": "/api/b/v1/{controller}", "DownstreamPathTemplate": "/api/b/v1/{controller}", "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT", "OPTIONS" ], "UseServiceDiscovery": false, "LoadBalancerOptions": { "Type": "RoundRobin" } } ] }
appsetting.json配置Apollo,这里三个服务配置都一样
{ "Apollo": { "AppId": "Peng.Core.Service", "Env": "DEV", "Namespaces": [ "Shared.json", "ocelotconfig.json" ], "MetaServer": "http://192.168.188.180:8080", "ConfigServer": [ "http://192.168.188.180:8080/" ] } }
(5)通过网关的IP访问接口