ASP.NET Core使用Ocelot創(chuàng)建API網(wǎng)關(guān)

API網(wǎng)關(guān)是我們系統(tǒng)的入口。它包含很多東西,比如路由,認(rèn)證,服務(wù)發(fā)現(xiàn),日志記錄等。

API Gateway

1、創(chuàng)建3個項目

項目名稱? ? ? ? ? ? ? ? ? ? ? ? ? ? ?項目類型

APIGateway? ? ? ? ? ? ? ? ? ? ? ? 空 ASP.NET Core 項目

CustomersAPIServices? ? ? ?ASP.NET Core Web API

ProductsAPIServices? ? ? ? ??ASP.NET Core Web API

解決方案目錄

2、完善2個 API Services 的功能

CustomersAPIServices項目中新建CustomersController

CustomersController.cs

指定CustomersAPIServices的服務(wù)地址

Program.cs

ProductsAPIServices項目中新建ProductsController

ProductsController.cs

指定ProductsAPIServices的服務(wù)地址

Program.cs

3、運(yùn)行 Customers 和 Products 服務(wù)

打開2個終端,使用 "dotnet run" 命令啟動 服務(wù)

啟動 Customers 服務(wù)
啟動 Products 服務(wù)
服務(wù)啟動成功

4、APIGateway項目中安裝 Ocelot 包

使用 NuGet 包管理器或程序包管理器控制臺安裝 Ocelot 包

5、添加 API Gateway 配置文件

新增 configuration.json 文件

configuration.json

該文件是API網(wǎng)關(guān)的配置文件。配置有兩個部分 - 一個ReRoutes數(shù)組和一個GlobalConfiguration。

ReRoutes是告訴Ocelot如何處理上游請求的對象。全局配置有點(diǎn)不方便,可以覆蓋ReRoute的特定設(shè)置。

6、項目中啟用 Ocelot

Program.cs

7、配置 Ocelot

Program.cs

8、運(yùn)行 API Gateway

運(yùn)行API Gateway

當(dāng)訪問?http://localhost:9000/products, 將會從?http://localhost:9002/api/products?服務(wù)中返回結(jié)果

當(dāng)訪問?http://localhost:9000/customers, 將會從?http://localhost:9001/api/customers?服務(wù)中返回結(jié)果

當(dāng)訪問?http://localhost:9000/customers/1, 將會從?http://localhost:9001/api/customers/1 服務(wù)中返回結(jié)果

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容