日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

浅析API网关——Ocelot[网关]+Consul[服务发现负载均衡]+Polly[服务熔断]+Ids4[服务认证]

發(fā)布時間:2023/12/20 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 浅析API网关——Ocelot[网关]+Consul[服务发现负载均衡]+Polly[服务熔断]+Ids4[服务认证] 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

API網(wǎng)關(guān)

本文將講述以下內(nèi)容:
概念------為什么------如何使用oclet-----內(nèi)部概念(上游和下游)、路由-----ocelot內(nèi)部運(yùn)行原理-----如何做步驟-----ocelot配置文件介紹----路由基本使用----路由負(fù)載均衡------路由consul支持-----路由多個服務(wù)操作-----路由多個服務(wù)聚合----路由限流----路由熔斷----路由緩存----路由身份驗(yàn)證。

1.什么是API網(wǎng)關(guān)

就是用來限制客戶端訪問服務(wù)端api一到門檻,在圖例中已經(jīng)進(jìn)行了展示

1.1 什么是API

API是Application Programming Interface縮寫,翻譯成中文就是應(yīng)用程序接口。在實(shí)際微服務(wù)中可以理解一個個功能方法。就比如你一個用戶服務(wù)的微服務(wù),可以對外提供 API 接口為,查找用戶,創(chuàng)建用戶等。

1.2 什么是網(wǎng)關(guān)

網(wǎng)關(guān), wiki 上定義。

在計(jì)算機(jī)網(wǎng)絡(luò)中,網(wǎng)關(guān)(英語:Gateway)是轉(zhuǎn)發(fā)其他服務(wù)器通信數(shù)據(jù)的服務(wù)器,接收從客戶端發(fā)送來的請求時,它就像自己擁有資源的源服務(wù)器一樣對請求進(jìn)行處理

2.為什么要使用微服務(wù)網(wǎng)關(guān)

2.1 大概有4四種情況

1、聚合微服務(wù)增多,導(dǎo)致客戶端不好維護(hù)

2、聚合微服務(wù)進(jìn)行集群

? 2.1 增加和修改聚合微服務(wù)集群,都要修改客戶端,導(dǎo)致客戶端不穩(wěn)定

? 2.2 服務(wù)集群,無法解決復(fù)雜均衡的問題

3、客戶端訪問多個聚合微服務(wù)

? 3.1 如果需要對客戶端身份驗(yàn)證和授權(quán),會導(dǎo)致每個服務(wù)都進(jìn)行授權(quán)

? 3.2 如何客戶端訪問過大,無法限制客戶端流量,導(dǎo)致系統(tǒng)宕機(jī)

? 3.3 如果客戶端訪問微服務(wù)系統(tǒng),每個微服務(wù)之間進(jìn)行調(diào)用。會導(dǎo)致耗時操作很難統(tǒng)計(jì)。

? 3.4 如果客戶端訪問微服務(wù)系統(tǒng),如何統(tǒng)計(jì)客戶端的調(diào)用日志

2.2 總結(jié):

1、聚合微服務(wù)增多,導(dǎo)致客戶端不好維護(hù)
2、聚合微服務(wù)進(jìn)行集群
2.1 增加和刪除聚合微服務(wù)集群節(jié)點(diǎn),都要去修改客戶端
2.2 服務(wù)集群,會有負(fù)載均衡問題
3、客戶端訪問聚合微服務(wù)
3.1 存在安全問題,
3.2 并發(fā)量大問題
3.3 性能調(diào)優(yōu)問題,鏈路追蹤
3.4 微服務(wù)訪問日志問題

3. 如何在項(xiàng)目中使用API網(wǎng)關(guān)

3.1 API網(wǎng)關(guān)類型

1、Netflix Zuul +java實(shí)現(xiàn)

2、Kong nginx +lua腳本實(shí)現(xiàn)

3、Tyk go語言開發(fā),收費(fèi)版本

4、Ocelot aspnetcore開發(fā)的

3.2 如何在項(xiàng)目中使用Ocelot

3.2.1 Ocelot是什么

簡單的來說Ocelot是一堆的asp.net core middleware組成的一個管道。當(dāng)它拿到請求之后會用一個request builder來構(gòu)造一個HttpRequestMessage發(fā)到下游的真實(shí)服務(wù)器,等下游的服務(wù)返回response之后再由一個middleware將它返回的HttpResponseMessage映射到HttpResponse上。

3.2.2 Ocelot內(nèi)部概念

上游

? Ocelot為上游:Upstream

下游

? Ocelot下面映射的服務(wù)為下游:Downstream

主要功能

1、路由

? 1.1 接受客戶端請求

? 1.2 獎客戶端請求轉(zhuǎn)換成下游地址

? 1.3 調(diào)用下游服務(wù),并返回結(jié)果

? 1.4 將下游服務(wù)返回的結(jié)果返回到前端

2、認(rèn)證

3、授權(quán)

4、負(fù)載均衡

5、鏈路監(jiān)控

6、限流

7、熔斷降級

8、請求聚合

9、Service Fabric

等其他功能

3.2.3 Ocelot文檔地址

中文文檔:http://www.jessetalk.cn/2018/03/19/net-core-apigateway-ocelot-docs/

英文文檔:https://ocelot.readthedocs.io/en/latest/introduction/gettingstarted.html

3.2.4 Ocelot如何使用

條件

1、aspnetcore3.1

2、Ocelot

3、團(tuán)隊(duì)微服務(wù)

4、ocelot.json文件

步驟

1、創(chuàng)建一個空的aspnetcore3.1項(xiàng)目

2、通過nuget安裝Ocelot

3、創(chuàng)建Ocelot配置文件ocelot.json

{"ReRoutes": [],"GlobalConfiguration": {"BaseUrl": "https://api.mybusiness.com"} }

要特別注意一下BaseUrl是我們外部暴露的Url,比如我們的Ocelot運(yùn)行在http://123.111.1.1的一個地址上,但是前面有一個 nginx綁定了域名http://api.jessetalk.cn,那這里我們的BaseUrl就是 http://api.jessetalk.cn。

4、加載ocelot.json配置文件

public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup<Startup>();webBuilder.ConfigureAppConfiguration((hostingContext, config) =>{// 1、加載ocelot配置文件config.AddJsonFile("ocelot.aggregate.json");});});

5、配置Ocelot依賴注入并加載配置文件

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

6、配置Ocelot中間件

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

3.2.5 Ocelot如何使用路由

一個路由完整配置
{"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 }
  • Downstream是下游服務(wù)配置
  • UpStream是上游服務(wù)配置
  • Aggregates 服務(wù)聚合配置
  • ServiceName, LoadBalancer, UseServiceDiscovery 配置服務(wù)發(fā)現(xiàn)
  • AuthenticationOptions 配置服務(wù)認(rèn)證
  • RouteClaimsRequirement 配置Claims鑒權(quán)
  • RateLimitOptions為限流配置
  • FileCacheOptions 緩存配置
  • QosOptions 服務(wù)質(zhì)量與熔斷
  • DownstreamHeaderTransform頭信息轉(zhuǎn)發(fā)
路由基本使用
{ "DownstreamPathTemplate": "/api/post/{postId}", "DownstreamScheme": "https", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 80, } ], "UpstreamPathTemplate": "/post/{postId}", "UpstreamHttpMethod": [ "Get"] }
  • DownstreamPathTemplate:下游路徑模板
  • DownstreamScheme:下游服務(wù)http schema
  • DownstreamHostAndPorts:下游服務(wù)的地址,如果使用LoadBalancer的話這里可以填多項(xiàng)
  • UpstreamPathTemplate: 上游也就是用戶輸入的請求Url模板
  • UpstreamHttpMethod: 上游請求http方法,可使用數(shù)組
路由負(fù)載均衡
{"DownstreamPathTemplate": "/api/posts/{postId}","DownstreamScheme": "https","DownstreamHostAndPorts": [{"Host": "10.0.1.10","Port": 5000,},{"Host": "10.0.1.11","Port": 5000,}],"UpstreamPathTemplate": "/posts/{postId}","LoadBalancerOptions": {"Type": "LeastConnection"},"UpstreamHttpMethod": [ "Put", "Delete" ] }

LoadBalancer將決定負(fù)載均衡的算法

  • LeastConnection – 將請求發(fā)往最空閑的那個服務(wù)器
  • RoundRobin – 輪流發(fā)送
  • NoLoadBalance – 總是發(fā)往第一個請求或者是服務(wù)發(fā)現(xiàn)
路由Consul負(fù)載均衡

條件:

1、Ocelot.Provider.Consul

2、Consul

3、Ocelot

步驟

1、通過nuget下載Ocelot.Provider.Consul

2、添加consul依賴注入

public void ConfigureServices(IServiceCollection services) {// 1、添加網(wǎng)關(guān)Ocelot到ioc容器services.AddOcelot().AddConsul(); }

3、路由consul配置

{"DownstreamPathTemplate": "/api/posts/{postId}","DownstreamScheme": "https","UpstreamPathTemplate": "/posts/{postId}","UpstreamHttpMethod": [ "Put" ],"ServiceName": "product","LoadBalancerOptions": {"Type": "LeastConnection"}, }
多個路由配置(多項(xiàng)目)

條件

1、TeamService,MemberService

2、ocelot.team.json,ocelot.member.json

步驟

1、創(chuàng)建ocelot.team.json,ocelot.member.json文件

2、配置動態(tài)加載ocelot.json配置文件

webBuilder.ConfigureAppConfiguration((hostingContext, config) => {config// .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)// .AddJsonFile("appsettings.json", true, true)// .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true).AddOcelot(hostingContext.HostingEnvironment);// .AddEnvironmentVariables(); });

會自動的加載配置文件,然后進(jìn)行合并,主要用于大項(xiàng)目配置

3、ocelot依賴注入配置

public void ConfigureServices(IServiceCollection services){// 1、添加網(wǎng)關(guān)Ocelot到ioc容器services.AddOcelot()}
路由聚合請求
{"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": "/"}] }

當(dāng)我們請求/的時候,會將/tom和/laura兩個結(jié)果合并到一個response返回

{"Tom":{"Age": 19},"Laura":{"Age": 25}}

需要注意的是:

  • 聚合服務(wù)目前只支持返回json
  • 目前只支持Get方式請求下游服務(wù)
  • 任何下游的response header并會被丟棄
  • 如果下游服務(wù)返回404,聚合服務(wù)只是這個key的value為空,它不會返回404

有一些其它的功能會在將來實(shí)現(xiàn)

  • 下游服務(wù)很慢的處理
  • 做一些像 GraphQL的處理對下游服務(wù)返回結(jié)果進(jìn)行處理
  • 404的處理
路由限流
"RateLimitOptions": {"ClientWhitelist": [],"EnableRateLimiting": true,"Period": "5m","PeriodTimespan": 1,"Limit": 1 }
  • ClientWihteList 白名單

  • EnableRateLimiting 是否啟用限流

  • Period 統(tǒng)計(jì)時間段:1s, 5m, 1h, 1d

  • PeroidTimeSpan 多少秒之后客戶端可以重試

  • Limit 在統(tǒng)計(jì)時間段內(nèi)允許的最大請求數(shù)量

    在 GlobalConfiguration下我們還可以進(jìn)行以下配置

"RateLimitOptions": {"DisableRateLimitHeaders": false,"QuotaExceededMessage": "Customize Tips!","HttpStatusCode": 999,"ClientIdHeader" : "Test" }
  • Http頭 X-Rate-Limit 和 Retry-After 是否禁用
  • QuotaExceedMessage 當(dāng)請求過載被截斷時返回的消息
  • HttpStatusCode 當(dāng)請求過載被截斷時返回的http status
  • ClientIdHeader 用來識別客戶端的請求頭,默認(rèn)是 ClientId
路由服務(wù)質(zhì)量與熔斷

條件

1、Ocelot.Provider.Polly

步驟

1、在ocelot上添加熔斷

public void ConfigureServices(IServiceCollection services) {// 1、添加網(wǎng)關(guān)Ocelot到ioc容器services.AddOcelot(new ConfigurationBuilder().AddJsonFile("ocelot.aggregate.json").Build()).AddConsul().AddPolly(); }

2、添加熔斷配置

熔斷的意思是停止將請求轉(zhuǎn)發(fā)到下游服務(wù)。當(dāng)下游服務(wù)已經(jīng)出現(xiàn)故障的時候再請求也是功而返,并且增加下游服務(wù)器和API網(wǎng)關(guān)的負(fù)擔(dān)。這個功能是用的Pollly來實(shí)現(xiàn)的,我們只需要為路由做一些簡單配置即可

"QoSOptions": {"ExceptionsAllowedBeforeBreaking":3,"DurationOfBreak":5,"TimeoutValue":5000 }
  • ExceptionsAllowedBeforeBreaking 允許多少個異常請求
  • DurationOfBreak 熔斷的時間,單位為秒
  • TimeoutValue 如果下游請求的處理時間超過多少則自動將請求設(shè)置為超時
路由緩存

Ocelot可以對下游請求結(jié)果進(jìn)行緩存 ,目前緩存的功能還不是很強(qiáng)大。它主要是依賴于CacheManager 來實(shí)現(xiàn)的,我們只需要在路由下添加以下配置即可

"FileCacheOptions": { "TtlSeconds": 15, "Region": "somename" }

Region是對緩存進(jìn)行的一個分區(qū),我們可以調(diào)用Ocelot的 administration API來移除某個區(qū)下面的緩存 。

路由認(rèn)證(Identity Server4)

步驟

Identity Server Bearer Tokens

添加Identity Server的認(rèn)證也是一樣

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(); }

Allowed Scopes

這里的Scopes將從當(dāng)前 token 中的 claims中來獲取,我們的鑒權(quán)服務(wù)將依靠于它來實(shí)現(xiàn) 。當(dāng)前路由的下游API需要某個權(quán)限時,我們需要在這里聲明 。和oAuth2中的 scope意義一致。

路由鑒權(quán)

我們通過認(rèn)證中的AllowedScopes 拿到claims之后,如果要進(jìn)行權(quán)限的鑒別需要添加以下配置

"RouteClaimsRequirement": {"UserType": "registered" }

當(dāng)前請求上下文的token中所帶的claims如果沒有 name=”UserType” 并且 value=”registered” 的話將無法訪問下游服務(wù)。

路由請求頭轉(zhuǎn)化

請求頭轉(zhuǎn)發(fā)分兩種:轉(zhuǎn)化之后傳給下游和從下游接收轉(zhuǎn)化之后傳給客戶端。在Ocelot的配置里面叫做Pre Downstream Request和Post Downstream Request。目前的轉(zhuǎn)化只支持查找和替換。我們用到的配置主要是 UpstreamHeaderTransform 和 DownstreamHeaderTransform

Pre Downstream Request

"Test": "http://www.bbc.co.uk/, http://ocelot.com/"

比如我們將客戶端傳過來的Header中的 Test 值改為 http://ocelot.com/之后再傳給下游

"UpstreamHeaderTransform": {"Test": "http://www.bbc.co.uk/, http://ocelot.com/" },

Post Downstream Request

而我們同樣可以將下游Header中的Test再轉(zhuǎn)為 http://www.bbc.co.uk/之后再轉(zhuǎn)給客戶端。

"DownstreamHeaderTransform": {"Test": "http://www.bbc.co.uk/, http://ocelot.com/" },

總結(jié)

以上是生活随笔為你收集整理的浅析API网关——Ocelot[网关]+Consul[服务发现负载均衡]+Polly[服务熔断]+Ids4[服务认证]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。