ASP.NET Core使用Ocelot创建API网关
API网关是我们系统的入口。它包含很多东西,比如路由,认证,服务发现,日志记录等。
API Gateway1、创建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的服务地址
Program.csProductsAPIServices项目中新建ProductsController
ProductsController.cs指定ProductsAPIServices的服务地址
Program.cs3、运行 Customers 和 Products 服务
打开2个终端,使用 "dotnet run" 命令启动 服务
启动 Customers 服务 启动 Products 服务 服务启动成功4、APIGateway项目中安装 Ocelot 包
使用 NuGet 包管理器或程序包管理器控制台安装 Ocelot 包
5、添加 API Gateway 配置文件
新增 configuration.json 文件
configuration.json该文件是API网关的配置文件。配置有两个部分 - 一个ReRoutes数组和一个GlobalConfiguration。
ReRoutes是告诉Ocelot如何处理上游请求的对象。全局配置有点不方便,可以覆盖ReRoute的特定设置。
6、项目中启用 Ocelot
Program.cs7、配置 Ocelot
Program.cs8、运行 API Gateway
运行API Gateway当访问 http://localhost:9000/products, 将会从 http://localhost:9002/api/products 服务中返回结果
当访问 http://localhost:9000/customers, 将会从 http://localhost:9001/api/customers 服务中返回结果
当访问 http://localhost:9000/customers/1, 将会从 http://localhost:9001/api/customers/1 服务中返回结果