API 为什么要网关?
不要网关可不可以,能跑吗?
当然可以,只是 API 多了后,就累,什么鉴权啊、日志啊、限流啊……哪个 API 服务器都要来一套,另外 API 一多,URL 满天飞,管都管不过来。
所以就出现了 API 网关,如同工厂只开一个门,而不是几十个门,管理起来就方便多了。
有哪些 API 网关产品
Kong、WSO2、eolink(中国)等。
而本文介绍的 Ocelot,是 .NET Core 下面的,它不是一个产品,而是一个组件,也就是说我们并不是拿回来安装上就能用,而是我们自己来开发。
Ocelot:[ˈɑːsəlɑːt],豹猫。
Ocelot 开始
工具
Visual Studio 2022 + .NET 6,Ocelot 需在 .NET 6 下面运行。
一、建立一个“ASP.NET Core Web API”项目
不做什么改动,它默认自带一个天气的示例,咱们就用它,待会儿让 Ocelot 来访问它。
二、建立一个“ASP.NET Core 空”项目
这个就是开始 Ocelot 项目了,后面都是针对此项目的操作。
三、添加 Ocelot
NuGet 中搜索 Ocelot,并安装。
四、添加 ocelot.json
{ "Routes": [ { "DownstreamPathTemplate": "/weatherforecast", "DownstreamScheme": "https", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 7219 } ], "UpstreamPathTemplate": "/tq", "UpstreamHttpMethod": [ "Get" ] } ] }
可以根据实际情况修改,大概意思就是说访问 tq 的时候,引流到 https://localhost:7219/weatherforecast。
五、修改 Program.cs
内容如下:
using Ocelot.Middleware; using Ocelot.DependencyInjection; new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { config .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) .AddJsonFile("appsettings.json", true, true) .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) .AddJsonFile("ocelot.json") .AddEnvironmentVariables(); }) .ConfigureServices(s => { s.AddOcelot(); }) .ConfigureLogging((hostingContext, logging) => { //add your logging }) .UseIISIntegration() .Configure(app => { app.UseOcelot().Wait(); }) .Build() .Run();
六、运行
Ctrl + F5 运行第一个项目。
Ctrl + F5 运行第二个项目。
浏览器中访问第二个项目,URL 后面跟 tq,结果返回了,返回的是第一个项目的结果。
说明生效了。
七、路由解说
可以看出关键是配置文件中的路由,路由默认是大小写敏感的,路由也可以使用变量。
{ "DownstreamPathTemplate": "/api/posts/{postId}", "DownstreamScheme": "https", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 80, } ], "UpstreamPathTemplate": "/posts/{postId}", "UpstreamHttpMethod": [ "Put", "Delete" ], "RouteIsCaseSensitive": false }
如上,使用 RouteIsCaseSensitive 关闭了大小写敏感,并使用 {} 实现了变量。
如果上流(上游)路径模板、下流(下游)路径模板都是 /{url},则是完全照搬、直接通达,这有助于减少我们写模板。
还有属性 Priority,表示优先级,值越小,优先级越低。
官方文档