Ocelot搭建api网关
2019-01-14 14:46:48 0 举报
AI智能生成
ocelot创建API网关
作者其他创作
大纲/内容
1.Ocelot简介
简单的来说Ocelot是一堆的asp.net core middleware组成的一个管道。当它拿到请求之后会用一个request builder来构造一个HttpRequestMessage发到下游的真实服务器,等下游的服务返回response之后再由一个middleware将它返回的HttpResponseMessage映射到HttpResponse上
2.Ocelot功能
路由、请求聚合、服务发现、认证、鉴权、限流熔断、并内置了负载均衡器与Service Fabric、Butterfly Tracing集成
3.演进
基本使用
集成Identity Server
网关集群
Consul 服务发现
分支主题
4.配置说明
Downstream是下游服务配置
UpStream是上游服务配置
Aggregates 服务聚合配置
ServiceName, LoadBalancer, UseServiceDiscovery 配置服务发现
AuthenticationOptions 配置服务认证
RouteClaimsRequirement 配置Claims鉴权
RateLimitOptions为限流配置
FileCacheOptions 缓存配置
QosOptions 服务质量与熔断
DownstreamHeaderTransform头信息转发
{
"DownstreamPathTemplate": "/",
"UpstreamPathTemplate": "/",
"UpstreamHttpMethod": [
"Get"
],
"AddHeadersToRequest": {},
"AddClaimsToRequest": {},
"RouteClaimsRequirement": {},
"AddQueriesToRequest": {},
"RequestIdKey": "",
"FileCacheOptions": {
"TtlSeconds": 0,
"Region": ""
},
"ReRouteIsCaseSensitive": false,
"ServiceName": "",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 51876,
}
],
"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
}
5.路由
基本使用
DownstreamPathTemplate:下游戏
DownstreamScheme:下游服务http schema
DownstreamHostAndPorts:下游服务的地址,如果使用LoadBalancer的话这里可以填多项
UpstreamPathTemplate: 上游也就是用户输入的请求Url模板
UpstreamHttpMethod: 上游请求http方法,可使用数组
{
"DownstreamPathTemplate": "/api/post/{postId}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 80,
}
],
"UpstreamPathTemplate": "/post/{postId}",
"UpstreamHttpMethod": [ "Get"]
}
路由负载均衡
LoadBalancer将决定负载均衡的算法
1.LeastConnection – 将请求发往最空闲的那个服务器
2.RoundRobin – 轮流发送
3.NoLoadBalance – 总是发往第一个请求或者是服务发现
{
"DownstreamPathTemplate": "/api/posts/{postId}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "10.0.1.10",
"Port": 5000,
},
{
"Host": "10.0.1.11",
"Port": 5000,
}
],
"UpstreamPathTemplate": "/posts/{postId}",
"LoadBalancer": "LeastConnection",
"UpstreamHttpMethod": [ "Put", "Delete" ]
}
6.请求聚合
需要注意的是:
1.聚合服务目前只支持返回json
2.目前只支持Get方式请求下游服务
3.任何下游的response header并会被丢弃
4.如果下游服务返回404,聚合服务只是这个key的value为空,它不会返回404
有一些其它的功能会在将来实现
1.下游服务很慢的处理
2.做一些像 GraphQL的处理对下游服务返回结果进行处理
3.404的处理
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/",
"UpstreamPathTemplate": "/laura",
"UpstreamHttpMethod": [
"Get"
],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 51881
}
],
"Key": "Laura"
},
{
"DownstreamPathTemplate": "/",
"UpstreamPathTemplate": "/tom",
"UpstreamHttpMethod": [
"Get"
],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 51882
}
],
"Key": "Tom"
}
],
"Aggregates": [
{
"ReRouteKeys": [
"Tom",
"Laura"
],
"UpstreamPathTemplate": "/"
}
]
}
{"Tom":{"Age": 19},"Laura":{"Age": 25}}
7.限流
这个功能就是我们的张善友添加进去的。优雅的实现了对请求进行限流可以防止下游服务器因为访问过载而崩溃
1.ClientWihteList 白名单
2.EnableRateLimiting 是否启用限流
3.Period 统计时间段:1s, 5m, 1h, 1d
4.PeroidTimeSpan 多少秒之后客户端可以重试
5.Limit 在统计时间段内允许的最大请求数量
"RateLimitOptions": {
"ClientWhitelist": [],
"EnableRateLimiting": true,
"Period": "1s",
"PeriodTimespan": 1,
"Limit": 1
}
在 GlobalConfiguration下我们还可以进行以下配置
1.Http头 X-Rate-Limit 和 Retry-After 是否禁用
2.QuotaExceedMessage 当请求过载被截断时返回的消息
3.HttpStatusCode 当请求过载被截断时返回的http status
4.ClientIdHeader 用来识别客户端的请求头,默认是 ClientId
"RateLimitOptions": {
"DisableRateLimitHeaders": false,
"QuotaExceededMessage": "Customize Tips!",
"HttpStatusCode": 999,
"ClientIdHeader" : "Test"
}
8.服务质量与熔断
当下游服务已经出现故障的时候再请求也是功而返,并且增加下游服务器和API网关的负担
1.ExceptionsAllowedBeforeBreaking 允许多少个异常请求
2.DurationOfBreak 熔断的时间,单位为秒
3.TimeoutValue 如果下游请求的处理时间超过多少则自如将请求设置为超时
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking":3,
"DurationOfBreak":5,
"TimeoutValue":5000
}
9.缓存
依赖于CacheManager 来实现
"FileCacheOptions": { "TtlSeconds": 15, "Region": "somename" }
10.认证
在ReRoutes的路由模板中的AuthenticationOptions进行配置,只需要我们的AuthenticationProviderKey一致即可
"ReRoutes": [{
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 51876,
}
],
"DownstreamPathTemplate": "/",
"UpstreamPathTemplate": "/",
"UpstreamHttpMethod": ["Post"],
"ReRouteIsCaseSensitive": false,
"DownstreamScheme": "http",
"AuthenticationOptions": {
"AuthenticationProviderKey": "TestKey",
"AllowedScopes": []
}
}]
public void ConfigureServices(IServiceCollection services)
{
var authenticationProviderKey = "TestKey";
var options = o =>
{
o.Authority = "https://whereyouridentityserverlives.com";
o.ApiName = "api";
o.SupportedTokens = SupportedTokens.Both;
o.ApiSecret = "secret";
};
services.AddAuthentication()
.AddIdentityServerAuthentication(authenticationProviderKey, options);
services.AddOcelot();
}
11.鉴权
通过认证中的AllowedScopes 拿到claims之后,如果要进行权限的鉴别需要添加以下配置
"RouteClaimsRequirement": {
"UserType": "registered"
}
当前请求上下文的token中所带的claims如果没有 name=”UserType” 并且 value=”registered” 的话将无法访问下游服务
12.请求头转化
13.Claims转化
14.Consul服务发现
后续探索
子主题 1 Service fabric + Ocelot + Identity Server4 + 52ABP
子主题 2 不够痛就别微服务
子主题 3 asp.net core webApi 参数保护 nuget 包 WeihanLi.DataProtection
微服务
好处
技术异构
弹性好(处理服务不可用和功能降级)
扩展方便,成本低
简化部署
与组织结构相匹配
可组合 易于重用完整的功能
对技术替代性的优化
缺点
性能(内存处理转化为远程调用)
可靠性 (远程调用失败的可能性)
最终一致性
操作的复杂性
初步架构
初步架构
收藏
0 条评论
下一页