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

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

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

ProductsAPIServices項目中新建ProductsController

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

3、運(yùn)行 Customers 和 Products 服務(wù)
打開2個終端,使用 "dotnet run" 命令啟動 服務(wù)



4、APIGateway項目中安裝 Ocelot 包
使用 NuGet 包管理器或程序包管理器控制臺安裝 Ocelot 包
5、添加 API Gateway 配置文件
新增 configuration.json 文件

該文件是API網(wǎng)關(guān)的配置文件。配置有兩個部分 - 一個ReRoutes數(shù)組和一個GlobalConfiguration。
ReRoutes是告訴Ocelot如何處理上游請求的對象。全局配置有點(diǎn)不方便,可以覆蓋ReRoute的特定設(shè)置。
6、項目中啟用 Ocelot

7、配置 Ocelot

8、運(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é)果