做者:markjiang7m2
原文地址:http://www.javashuo.com/article/p-arjfcwsg-er.html
源码地址:https://gitee.com/Sevenm2/OcelotDemohtml
今天要给你们介绍的Ocelot是一个基于 .net core的开源WebAPI服务网关项目,它的功能很是强大,包括了路由、请求聚合、服务发现、认证鉴权、限流、负载均衡等功能。而这些功能均可以直接经过修改json配置文件便可使用,很是方便。Ocelot是系统中对外暴露的一个请求入口,全部外部接口都必须经过这个网关才能向下游API发出请求,就如地铁中的安检系统,全部人都必须通过安检才能乘坐地铁。git
我将经过具体案例对Ocelot的功能进行一一展开说明,而本文中涉及案例的完整代码均可以从个人代码仓库进行下载。github
经过VS2017新建一个基于 .net core WebAPI项目,而后经过nuget直接搜索Ocelot
或者使用如下命令行添加Ocelot的引用。json
Install-Package Ocelot
在项目的根目录添加一个.json
配置文件,文件名自定义,此案例为Ocelot.json.添加配置以下:c#
{ "ReRoutes": [], "GlobalConfiguration": { } }
能够看到在咱们的配置文件中包含两个配置项,ReRoutes是一个数组,将会包含服务器的路由配置,GlobalConfiguration则是一个全局配置项。我会在下文中经过各类案例详细说明配置项中的具体内容以及如何使用,所以,在这里暂时不展开说明。
将该配置文件添加到 .net core configuration中
Program.csapi
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, builder) => { builder.AddJsonFile("Ocelot.json"); }) .UseStartup<Startup>();
由于 .net core支持当配置文件被修改后会从新加载,因此若是咱们须要支持从新加载,可修改成:数组
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, builder) => { builder.AddJsonFile("Ocelot.json", optional: false, reloadOnChange: true); }) .UseStartup<Startup>();
将Ocelot做为中间件注册,须要添加两个命名空间
Startup.cs缓存
using Ocelot.DependencyInjection; using Ocelot.Middleware;
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddOcelot(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); app.UseOcelot().Wait(); }
至此,咱们的Ocelot就已经搭建完成了。下面咱们经过具体案例来讲明如何修改配置进行相关功能的使用。服务器
咱们先来认识一下到底包含哪些参数,以及这些参数的含义。前面咱们有介绍到,配置文件中包含两个配置项:ReRoutes和GlobalConfiguration。
咱们先来看GlobalConfiguration,它是一个全局配置项,一般咱们都要在这个配置项中添加一个属性BaseUrl
,BaseUrl就是Ocelot服务对外暴露的Url。app
"GlobalConfiguration": { "BaseUrl": "http://localhost:4727" }
ReRoutes是一个数组,其中的每个元素表明了一个路由,而一个路由所包含的全部可配置参数以下:
{ "DownstreamPathTemplate": "/", "UpstreamPathTemplate": "/", "UpstreamHttpMethod": [ "Get" ], "AddHeadersToRequest": {}, "AddClaimsToRequest": {}, "RouteClaimsRequirement": {}, "AddQueriesToRequest": {}, "RequestIdKey": "", "FileCacheOptions": { "TtlSeconds": 0, "Region": "" }, "ReRouteIsCaseSensitive": false, "ServiceName": "", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 8001, } ], "QoSOptions": { "ExceptionsAllowedBeforeBreaking": 0, "DurationOfBreak": 0, "TimeoutValue": 0 }, "LoadBalancer": "", "RateLimitOptions": { "ClientWhitelist": [], "EnableRateLimiting": false, "Period": "", "PeriodTimespan": 0, "Limit": 0 }, "AuthenticationOptions": { "AuthenticationProviderKey": "", "AllowedScopes": [] }, "HttpHandlerOptions": { "AllowAutoRedirect": true, "UseCookieContainer": true, "UseTracing": true }, "UseServiceDiscovery": false }
固然,咱们在实际使用过程当中不须要设置全部的参数,只须要根据实际须要进行配置便可。
路由是Ocelot最基本的功能。Ocelot接收到来自上游服务的请求,通过验证后,将请求转发到下游服务,所以,咱们首先要配置路由当中上下游服务参数。
{ "DownstreamPathTemplate": "/api/ocelot/{Id}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 8001, } ], "UpstreamPathTemplate": "/ocelot/{Id}", "UpstreamHttpMethod": ["Get"] }
{}
中的内容表明动态参数所以,当上游服务向地址http://localhost:4727/ocelot/5
发出请求时,Ocelot会将请求转发到下游服务http://localhost:8001/api/ocelot/5
。
本案例提供了下游服务Demo - OcelotDownAPI,将OcelotDownAPI发布到IIS端口便可使用。下游服务在接收到请求后返回一个字符串用于代表本身的身份。
[HttpGet("{id}")] public async Task<IActionResult> Get(int id) { var result = await Task.Run(() => { return $"This is from {HttpContext.Request.Host.Value}, path: {HttpContext.Request.Path}"; }); return Ok(result); }
测试结果:
若是但愿Ocelot可以转发全部的请求,则能够配置以下:
{ "DownstreamPathTemplate": "/{url}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 8001, } ], "UpstreamPathTemplate": "/{url}", "UpstreamHttpMethod": ["Get"] }
这样就能将全部Get请求转发到下游服务。不过这样配置的优先级是最低的,一旦匹配到其它路由模板,会优先选择。
若是但愿Ocelot只转发来自某个特定上游服务Host的请求,则能够配置以下:
{ "DownstreamPathTemplate": "/{url}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 8001, } ], "UpstreamPathTemplate": "/{url}", "UpstreamHttpMethod": ["Get"], "UpstreamHost": "localhost:4023" }
这样Ocelot就只会转发来自localhost:4023的请求。须要注意的是,若是路由配置中包含两个除UpstreamHost
之外都相同的路由,即其中一个带有UpstreamHost
,而另一个没有,则Ocelot会优先选择带有UpstreamHost
的路由。
设置路由的优先级。咱们能够定义ReRoutes
路由数组中响应的优先级。0是最低的优先级,数字越大,优先级越高。
[ { "UpstreamPathTemplate": "/ocelot/{Id}" "Priority": 0 }, { "UpstreamPathTemplate": "/ocelot/10" "Priority": 1 }, ]
本文主要介绍了Ocelot的功能,并经过简单的案例讲述如何构建Ocelot网关以及对Ocelot的基本应用。因为Ocelot功能很是的强大,若是将全部的案例都放到同一篇文章中会致使篇幅过长,不便于阅读,所以,我将会针对Ocelot功能写成系列文章,但愿你们继续捧场。
参考文献
本文在编写过程当中引用或参考了如下文章中的部份内容,若有侵权,请联系修改或删除。
https://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html