net

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

2018-06-05  本文已影响703人  不服高人_有罪

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 服务中返回结果

上一篇 下一篇

猜你喜欢

热点阅读