一、介绍

Ocelot 是基于.NetCore实现的开源的API网关,支持IdentityServer认证。Ocelot具有路由、请求聚合、服务发现、认证、鉴权、限流熔断等功能,并内置了负载均衡器与Service Fabric、Butterfly Tracing集成。

Ocelot本质是由一系列特定顺序的.Net Core Middleware组成的一个管道。Ocelot接收到请求之后,用request bulider来创建一个HttpRequestMessage对象,该对象根据配置将请求下发给下游指定的服务器进行请求处理。下游服务返回response之后,一个middleware将它返回的HttpResponseMessage 映射到HttpResponse,再转发给客户端。

二、如何搭建一个Ocelot项目

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/values", // 下游游请求模板
"DownstreamScheme": "http", //下游服务 schema
"UpstreamPathTemplate": "/api/values", // 上游请求模板
"UpstreamHttpMethod": [ "Get" ], // 上游请求http方法
//下游服务的地址,如果使用LoadBalancer的话这里可以填多项
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8802
}
],
//LeastConnection – 将请求发往最空闲的那个服务器
//"RoundRobin""轮流发送"
//"NoLoadBalance" "总是发往第一个请求或者是服务发现",
"LoadBalancer": "LeastConnection",
//熔断配置
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3, //允许的异常请求数
"DurationOfBreak": 10, //熔断的时间,单位为秒
"TimeoutValue": 5000 //如果下游请求的处理时间超过多少则将请求设置为超时
},
//缓存配置
"FileCacheOptions": {
"TtlSeconds": 10,
"Region": "somename" //是对缓存进行的一个分区
},
"HttpHandlerOptions": {
"AllowAutoRedirect": false,
"UseCookieContainer": false
},
//配置服务认证
"AuthenticationOptions": {
"AuthenticationProviderKey": "",
"AllowedScopes": []
}
},
{
"DownstreamPathTemplate": "/api/product",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/api/product",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8801
}
],
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3,
"DurationOfBreak": 10,
"TimeoutValue": 5000
},
"AuthenticationOptions": { }
}
],
"GlobalConfiguration": {
"RequestIdKey": "OcRequestId",
"AdministrationPath": "/admin"
}
}

将配置文件加入Configuration

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostcontext, bulid) => {
bulid.SetBasePath(hostcontext.HostingEnvironment.ContentRootPath)
.AddJsonFile("ocelot.json");
})
.UseKestrel()
.UseIISIntegration()
.UseStartup<Startup>();
}

添加依赖注入

       public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot();
}

添加Ocelot中间件

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
} app.UseOcelot().Wait();
}

添加两个下游api服务,对应ocelot.json配置的下游服务

初探.Net Core API 网关Ocelot(一)-LMLPHP

启动项目

三、参考

[1] .NET Core开源API网关 – Ocelot中文文档

[2] Ocelot GitHub

05-12 22:54