查看原文
其他

.NET Core使用Ocelot网关负载,限流,熔断,Header转换

DotNet 2021-09-23

(给DotNet加星标,提升.Net技能


转自:她微笑的脸
cnblogs.com/linhuiy/p/12029652.html

一、什么是API网关


API网关是微服务架构中的唯一入口,它提供一个单独且统一的API入口用于访问内部一个或多个API。


它可以具有身份验证,监控,负载均衡,缓存,请求分片与管理,静态响应处理等。API网关方式的核心要点是,所有的客户端和消费端都通过统一的网关接入微服务,在网关层处理所有的非业务功能。通常,网关也是提供REST/HTTP的访问API。服务端通过API-GW注册和管理服务。


二、Ocelot介绍


Ocelot是用.NET Core实现的一款开源的网关,Ocelot其实就是一组按照顺序排列的.net core中间件。它接受到请求之后用request builder构建一个HttpRequestMessage对象并发送到下游服务,当下游请求返回到Ocelot管道时再由一个中间件将HttpRequestMessage映射到HttpResponse上返回客户端。


开源地址:hhttps://github.com/ThreeMammals/Ocelot


三、使用Ocelot傻瓜式转发


新建三个项目webApi项目,分别命名为ApiGateway,Api_A,Api_B



设置Api_A端口为5001,Api_B端口为5002,ApiGateway为5000


为ApiGateway项目安装Ocelot,在Nuget中搜索Ocelot或者直接使用Install-Package Ocelot进行安装。最新版本为13.8.x支持core3.0。


在ApiGateway新建一个configuration.json配置文件。


{
"ReRoutes": [
{
//上游Api请求格式
"UpstreamPathTemplate": "/Api_A/{controller}/{action}",
//网关转发到下游格式
"DownstreamPathTemplate": "/api/{controller}/{action}",
//上下游支持请求方法
"UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
"DownstreamScheme": "http",
//下游服务配置
"DownstreamHostAndPorts": [
{
//下游地址
"Host": "localhost",
//下游端口号
"Port": 5001
}
]
},
{
"UpstreamPathTemplate": "/Api_B/{controller}/{action}",
"DownstreamPathTemplate": "/api/{controller}/{action}",
"UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5002
}
]
}
]
}


在Startup.cs 的ConfigureServices和Configure中配置Ocelot


public void ConfigureServices(IServiceCollection services)
{ services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddOcelot(new ConfigurationBuilder()
.AddJsonFile("configuration.json")
.Build());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseOcelot();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}


分别为Api_A,和Api_B分别添加一个print接口。


[HttpGet("print")]
public string Print()
{
return "Api_A";
}
[HttpGet("print")]
public string Print()
{
return "Api_B";
}


四、测试网关


启动三个项目,使用postman来调用网关


访问Api_A服务



访问Api_B服务



可以看到网关通过接受到的请求的Url后通过我们的配置自动转发到了我们想要访问的服务。


五、网关的负载均衡


当下游拥有多个节点的时候,我们可以用DownstreamHostAndPorts来配置


{
"UpstreamPathTemplate": "/Api_A/{controller}/{action}",
"DownstreamPathTemplate": "/api/{controller}/{action}",
"DownstreamScheme": "https",
"LoadBalancer": "LeastConnection",
"UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
"DownstreamHostAndPorts": [
{
"Host": "127.0.0.1",
"Port": 5001,
},
{
"Host": "127.00.1",
"Port": 5002,
}
],
}


  • LoadBalancer是来决定负载的算法


  • LeastConnection:将请求发往最空闲的那个服务器


  • RoundRobin:轮流转发


  • NoLoadBalance:总是发往第一个请求或者是服务发现


限流


限流可以防止上下游服务器因为过载而崩溃,可以使用RateLimitOptions来配置限流


{
"RateLimitOptions": {
"ClientWhitelist": [“127.0.0.1”],
"EnableRateLimiting": true,
"Period": "5s",
"PeriodTimespan": 1,
"Limit": 10
}
}


  • ClientWihteList:白名单,不受限流控制。


  • EnableRateLimiting:使用启用限流。


  • Period:限流控制的时间段 1s, 5m, 1h, 1d。


  • PeroidTimeSpan:超过限流限制的次数后,需要等待重置的时间(单位是秒)。


  • Limit:在限流控制时间段内最大访问数。

    对于除了请求头中ClientId=127.0.0.1的意外所有求情启用限流,5秒该api最多10次,如果达到10次需要从第10次请求闭合后等待一秒进行下一次访问。


超过限流后会返回429状态码,并在在返回头(Response Header)的Retry-After属性中返回等待重置时间。



限流的默认提示,code码,和限制标志都是可以自己配置的


{
"GlobalConfiguration": {
"BaseUrl":"www.baidu.com",
"RateLimitOptions": {
"DisableRateLimitHeaders": false,
"QuotaExceededMessage": "接口限流!",
"HttpStatusCode": 200,
"ClientIdHeader": "ClientId"
}
}


  • DisableRateLimitHeaders:是否显示X-Rate-Limit和Retry-After头


  • QuotaExceededMessage:提示信息


  • HttpStatusCode:状态码


  • ClientIdHeader:用来设别客户请求头,默认为ClientId。


  • BaseUrl 网关暴露的的地址。


熔断


熔断是在下游服务故障或者请求无响应的时候停止将请求转发到下游服务。


{
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3,
"DurationOfBreak": 20,
"TimeoutValue": 5000
}
}


  • ExceptionsAllowedBeforeBreaking:允许多少个异常请求。


  • DurationOfBreak:熔断的时间(秒)。


  • TimeoutValue:下游请求的处理时间超过多少则将请求设置为超时。


缓存


Ocelot可以对下游请求结果进行缓存,主要是依赖于CacheManager来实现的。


{
"FileCacheOptions": {
"TtlSeconds": 60,
"Region": "key"
}
}



  • TtlSeconds:缓存时间(秒)。


  • Region:缓存分区名

我们可以调用Ocelot的API来移除某个区下面的缓存 。


请求头的转化


Ocelot允许在请求下游服务之前和之后转换Header.目前Ocelot只支持查找和替换.


如果们需要转发给下游的Header重添加一个key/value


{
"UpstreamHeaderTransform": {
"demo": "xxxxxxx"
}
}


如果们需要在返回给客户端的的Header中添加一个key/value


{
"DownstreamHeaderTransform": {
"demo": "xxxxxxx"
}
}


如果我们需要替换Heaher中某些值


{
//请求
"UpstreamHeaderTransform": {
"demo": "a,b"
},
//响应
"DownstreamHeaderTransform":
{
"demo": "a,b"
}
}


语法是{find},{replace}, 利用b取代a


在Header转换中可以使用占位符


  • {BaseUrl} - 这个是Ocelot暴露在外的url. 例如http://localhost:5000/.


  • {DownstreamBaseUrl} - 这个是下游服务的基本url 例如http://localhost:5001/. 目前这个只在DownstreamHeaderTransform中起作用.


  • {TraceId} - 这个是Butterfly的跟踪id.目前这个也只在DownstreamHeaderTransform中起作用


如果您想将location头返回给客户端,可能需要将location更改为Ocelot的地址而不是下游服务地址。Ocelot可以使用以下配置实现。


{
"DownstreamHeaderTransform": {
"Location": "{DownstreamBaseUrl},{BaseUrl}"
},
}


给Header中添加下游地址



响应的Header中已经替换成BaseUrl了



总结


简单的实现了通过网关来访问api接口。ocelot功能远不止这些,之后会实现与IdentityServer的认证鉴权。服务发现。


推荐阅读

(点击标题可跳转阅读)

.NET Core 跨平台基础框架 xms 发布了

.NET Core 通用权限管理系统Blazor版本

不一样的角度一窥多线程

看完本文有收获?请转发分享给更多人

关注「DotNet」加星标,提升.Net技能 

好文章,我在看❤️

: . Video Mini Program Like ,轻点两下取消赞 Wow ,轻点两下取消在看

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存