.NET Core微服務二:Ocelot API網關


.NET Core微服務一:Consul服務中心

.NET Core微服務二:Ocelot API網關

.NET Core微服務三:polly熔斷與降級

 

本文的項目代碼,在文章結尾處可以下載。

本文使用的環境:Windows10 64位 + VS 2019 + .NET Core 3.1 + Ocelot 14.0.3

Ocelot 相關地址:

https://github.com/ThreeMammals/Ocelot

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

 

Ocelot 單獨使用,可以查看“Ocelot的簡單使用”這篇文章

本文接着“.NET Core微服務一:Consul服務中心”這篇文章,通過cmd運行起“Student”和“Teacher”服務,接下來就是創建網關項目

 

一、新建webapi項目,命名為“Ocelot_Consul”,去掉HTTPS勾選,不需要Controller,改為控制台方式啟動

 

二、打開程序包管理器控制台,依次執行命令:

Install-Package Ocelot
Install-Package Ocelot.Provider.Consul

 

 

三、在項目根目錄下,新建配置文件“ocelot.json”

"LoadBalancer"負載均衡類型:

RoundRobin:輪詢機制,循環找到可以用的服務

LeastConnection:最少連接數,跟蹤發現現在有最少請求或處理的可用服務

NoLoadBalancer:不使用負載均衡,直接訪問第一個發現的可用的服務

 1 {
 2   "ReRoutes": [
 3     {
 4       "DownstreamPathTemplate": "/api/Default/GetList",
 5       "DownstreamScheme": "http",
 6       "UpstreamPathTemplate": "/api/v1/Student/GetList",
 7       "UpstreamHttpMethod": [ "Get" ],
 8       "ServiceName": "Student",
 9       "LoadBalancerOptions": {
10         "Type": "RoundRobin"
11       },
12       "UseServiceDiscovery": true
13       //  ,
14       //"RateLimitOptions": {
15       //  "ClientWhitelist": [], //白名單
16       //  "EnableRateLimiting": true, //是否限流
17       //  "Period": "30s", //指定一個時間
18       //  "PeriodTimespan": 10, //多少時間后,可以重新請求。
19       //  "Limit": 5 //在Period的指定時間內,最多請求次數
20       //}
21     },
22     {
23       "DownstreamPathTemplate": "/api/Default/GetList",
24       "DownstreamScheme": "http",
25       "UpstreamPathTemplate": "/api/v1/Teacher/GetList",
26       "UpstreamHttpMethod": [ "Get" ],
27       "ServiceName": "Teacher",
28       "LoadBalancerOptions": {
29         "Type": "RoundRobin"
30       },
31       "UseServiceDiscovery": true
32     }
33   ],
34 
35   "GlobalConfiguration": {
36     "ServiceDiscoveryProvider": {
37       "Host": "127.0.0.1",
38       "Port": 8500
39     }
40   }
41 }

 

四、在Program.cs的CreateHostBuilder中加入

.ConfigureAppConfiguration(conf => {
    conf.AddJsonFile("ocelot.json", false, true); })

 

五、找到Startup.cs

在ConfigureServices中加入:

services.AddOcelot().AddConsul();

在Configure中加入:

app.UseOcelot().Wait();

 

六、通過VS啟動“Ocelot_Consul”,由於“ocelot.json”配置的對外的路由

“Student”服務的訪問地址為:http://localhost:5000/api/v1/Student/GetList

“Teacher”服務的訪問地址為:http://localhost:5000/api/v1/Teacher/GetList

  

 

 

 

代碼:https://files.cnblogs.com/files/shousiji/Ocelot_Consul.rar

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM