.NET Core微服務開發網關篇-ocelot
- 2020 年 7 月 15 日
- 筆記
- .Net Core 3.X, Ocelot, 微服務
通過上篇我們知道,網關是外部訪問的統一入口,本文採用Ocelot作為Api網關。
環境要求:
-
vs2019
-
.NetCore3.1
-
Ocelot16.0.1
創建一個產品服務Api站點(AAStore.ProductCatalog.Api)
添加一個ProductController
[Route("api/[controller]")] [ApiController] public class ProductController : ControllerBase { [HttpGet(template:"Get")] public string GetProductById() { return "Product service"; } }
運行瀏覽
然後再創建一個訂單服務Api站點(AAStore.Orde.Api)
添加一個OrderController
[Route("api/[controller]")] [ApiController] public class OrderController : ControllerBase { [HttpGet(template:"Get")] public string GetOrder() { return "Order Service"; } }
運行瀏覽
兩個服務已經已經準備好了,最後創建一個網關站點(AAStore.WebApiGateway)
-
安裝Ocelot
創建一個json配置文件(ocelot.json)
{ "Routes": [ { "DownstreamPathTemplate": "/api/Product/get", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 8081 } ], "UpstreamPathTemplate": "/api/Product/{everything}", "UpstreamHttpMethod": [ "Get" ] }, { "DownstreamPathTemplate": "/api/Order/get", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 8082 } ], "UpstreamPathTemplate": "/api/Order/get", "UpstreamHttpMethod": [ "Get" ] } ] }
ocelot api網關的主要功能是接收傳入的HTTP請求並將其轉發到下游服務,目前作為一個HTTP請求。Ocelot將一個請求到另一個請求的路由描述為Routes。
DownstreamPathTemplate、Scheme 和 DownstreamHostAndPorts 構成要將此請求轉發到的內部微服務 URL。
端口是服務使用的內部端口。使用容器時,在其 dockerfile 中指定端口。Host 是一個服務名稱,取決於使用的服務名稱解析。使用 docker-compose 時,服務名稱由 Docker 主機提供,它使用 docker-compose 文件中提供的服務名稱。如果使用 Kubernetes 或 Service Fabric 等業務流程協調程序,則應通過每個業務流程協調程序提供的 DNS 或名稱解析來解析該名稱。
DownstreamHostAndPorts 是一個數組,包含要將請求轉發到的任何下游服務的主機和端口。通常這隻包含一個條目,但有時可能想要將均衡請求加載到下游服務,而通過 Ocelot 即可添加多個條目,然後選擇負載均衡器。但是如果使用 Azure 和任何業務流程協調程序,那麼通過雲和業務流程協調程序基礎結構進行負載均衡可能會更好。
UpstreamPathTemplate 是一個 URL,Ocelot 將其用來識別用於客戶端中給定請求的 DownstreamPathTemplate。最後,使用了 UpstreamHttpMethod,因此 Ocelot 可區分對相同 URL 的不同的請求(GET、POST、PUT)。
注意: ocelot16.x版本之後的配置節點寫為Routes,而非ReRoutes 否則會報錯(Failed to mat ch Route configuration for upstream path)。
-
在Program.cs 通過AddJsonFile方法向生成器提供ocelot.json文件、添加Ocelot服務(AddOcelot)和添加ocelot中間件(UseOcelot)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureAppConfiguration((hostingContext, config) => { config .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) .AddJsonFile("ocelot.json") .AddEnvironmentVariables(); ; }) .ConfigureServices(services => { services.AddOcelot(); services.AddHttpContextAccessor(); }) .Configure(app => { app.UseOcelot().Wait(); }); });
然後運行網關,通過網關訪問產品、訂單微服務:
如果運氣好的話,跟着一步一步做,你也可以運行成功。當然ocelot還有很多功能如:路由、請求聚合、服務發現、WebSockets、認證、授權、LB、K8S、限流、熔斷等等。
參考//docs.microsoft.com/zh-cn/dotnet/architecture/microservices/multi-container-microservice-net-applications/implement-api-gateways-with-ocelot