ASP.NET Core使用Ocelot创建API网关

API网关是我们系统的入口。它包含很多东西,比如路由,认证,服务发现,日志记录等。

API Gateway

1、创建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.cs

ProductsAPIServices项目中新建ProductsController

ProductsController.cs

指定ProductsAPIServices的服务地址

Program.cs

3、运行 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.cs

7、配置 Ocelot

Program.cs

8、运行 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 服务中返回结果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容