【Part 1】在ASP.NET Core中使用Ocelot构建API网关

Introduction

在本文中,您将学习一种在ASP.NET Core中使用Ocelot构建API网关的简单方法也许你会问,什么是API网关。

让我们先看看下面的截图。

ASP.NET Core

上面的屏幕截图可以帮助您清楚地理解它。

API网关是我们系统的入口。 它包含许多内容,例如路由,身份验证,服务发现,日志记录等。

Ocelot

Ocelot面向使用.NET运行微服务/面向服务的体系结构的人员,这些人员需要在系统中具有统一的入口点。 您可以访问该项目的Github页面以找到更多信息。

我将使用一个简单的演示向您展示如何使用Ocelot。

Let's begin!

Step 1

首先创建三个项目

Project Name Project Type Description
APIGateway ASP.NET Core Empty entry of this demo
CustomersAPIServices ASP.NET Core Web API API Service that handles something about customers
ProductsAPIServices ASP.NET Core Web API API Service that handles something about products

ASP.NET Core

Step 2

首先完成两个API服务。 在CustimersAPIServices项目中创建一个CustomerController。

  1. [Route("api/[controller]")]  
  2. public class CustomersController : Controller  
  3. {          
  4.     [HttpGet]  
  5.     public IEnumerable<string> Get()  
  6.     {  
  7.         return new string[] { "Catcher Wong", "James Li" };  
  8.     }  
  9.   
  10.     [HttpGet("{id}")]  
  11.     public string Get(int id)  
  12.     {  
  13.         return $"Catcher Wong - {id}";  
  14.     }              
  15. }  

为了指定此服务的App URL,我们应该在Program类中添加UseUrls。

  1. public static IWebHost BuildWebHost(string[] args) =>  
  2.         WebHost.CreateDefaultBuilder(args)  
  3.             .UseStartup<Startup>()  
  4.             .UseUrls("http://localhost:9001")  
  5.             .Build();  

在ProductsAPIServices项目中创建一个ProductsController。

 
  1. [Route("api/[controller]")]  
  2. public class ProductsController : Controller  
  3. {  
  4.     [HttpGet]  
  5.     public IEnumerable<string> Get()  
  6.     {  
  7.         return new string[] { "Surface Book 2", "Mac Book Pro" };  
  8.     }  
  9. }  

编辑Program类以添加UseUrls。

 
  1. public static IWebHost BuildWebHost(string[] args) =>  
  2.         WebHost.CreateDefaultBuilder(args)  
  3.             .UseStartup<Startup>()  
  4.             .UseUrls("http://localhost:9002")  
  5.             .Build();  

Note

您还可以在“项目选项”页面中指定应用程序URL。

ASP.NET Core

Step 3

运行客户服务和产品服务。

打开两个终端,然后使用“ dotnet run”命令启动它们。

ASP.NET Core

如您所见,客户服务正在监听http:// localhost:9001,产品服务正在监听http:// localhost:9002。

打开浏览器,验证服务是否正常。

ASP.NET Core

 
幸运的是,一切进展顺利。

Step 4

现在,我们应该转到APIGateway项目。 我们应该首先安装Ocelot软件包。

Install-Package Ocelot

安装此软件包后,您可以找到对它的依赖。

ASP.NET Core

Step 5

添加configuration.json文件。

 
  1. {  
  2.     "ReRoutes": [  
  3.         {  
  4.             "DownstreamPathTemplate": "/api/customers",  
  5.             "DownstreamScheme": "http",  
  6.             "DownstreamHost": "localhost",  
  7.             "DownstreamPort": 9001,  
  8.             "UpstreamPathTemplate": "/customers",  
  9.             "UpstreamHttpMethod": [ "Get" ]  
  10.         },  
  11.         {  
  12.             "DownstreamPathTemplate": "/api/customers/{id}",  
  13.             "DownstreamScheme": "http",  
  14.             "DownstreamHost": "localhost",  
  15.             "DownstreamPort": 9001,  
  16.             "UpstreamPathTemplate": "/customers/{id}",  
  17.             "UpstreamHttpMethod": [ "Get" ]  
  18.         },  
  19.         {  
  20.             "DownstreamPathTemplate": "/api/products",  
  21.             "DownstreamScheme": "http",  
  22.             "DownstreamPort": 9002,  
  23.             "DownstreamHost": "localhost",  
  24.             "UpstreamPathTemplate": "/api/products",  
  25.             "UpstreamHttpMethod": [ "Get" ]  
  26.         }  
  27.     ],  
  28.     "GlobalConfiguration": {  
  29.         "RequestIdKey": "OcRequestId",  
  30.         "AdministrationPath": "/administration"  
  31.     }  
  32. }  

此文件是API网关的配置。 配置分为两部分-ReRoutes数组和GlobalConfiguration。

ReRoute是告诉Ocelot如何处理上游请求的对象。 全局配置有点怪异,并允许覆盖ReRoute特定设置。

采取这一部分来解释“ReRoutes section”。

 
  1. {  
  2.     "DownstreamPathTemplate": "/api/customers/{id}",  
  3.     "DownstreamScheme": "http",  
  4.     "DownstreamHost": "localhost",  
  5.     "DownstreamPort": 9001,  
  6.     "UpstreamPathTemplate": "/customers/{id}",  
  7.     "UpstreamHttpMethod": [ "Get" ]  
  8. }  

这些项目以“Downstream”开头,这意味着我们的请求将转发到http:// localhost:9001 / api / customers / {id}。

这些项目以"Upstream"开头,这意味着我们应该对/ customers / {id}`使用HTTP GET方法来访问此服务。

Step 6

编辑Startup类,以便我们可以在该项目中使用Ocelot。

 
  1. public class Startup  
  2. {  
  3.     public Startup(IHostingEnvironment env)  
  4.     {  
  5.         var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();  
  6.         builder.SetBasePath(env.ContentRootPath)      
  7.                //add configuration.json  
  8.                .AddJsonFile("configuration.json", optional: false, reloadOnChange: true)  
  9.                .AddEnvironmentVariables();  
  10.   
  11.         Configuration = builder.Build();  
  12.     }  
  13.   
  14.     //change  
  15.     public IConfigurationRoot Configuration { get; }  
  16.   
  17.     public void ConfigureServices(IServiceCollection services)  
  18.     {  
  19.         Action<ConfigurationBuilderCachePart> settings = (x) =>  
  20.         {  
  21.             x.WithMicrosoftLogging(log =>  
  22.             {  
  23.                 log.AddConsole(LogLevel.Debug);  
  24.   
  25.             }).WithDictionaryHandle();  
  26.         };  
  27.         services.AddOcelot(Configuration, settings);  
  28.     }  
  29.       
  30.     //don't use Task here  
  31.     public async void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  32.     {  
  33.         await app.UseOcelot();  
  34.     }  
  35. }  

不要忘记将configuration.json文件添加到Configuration中。

Step 7

这是配置Ocelot的非常重要的步骤。

我们应该创建一个IWebHostBuilder的新实例。 而且,不要在这里使用var !!!

 
  1. public class Program  
  2. {  
  3.     public static void Main(string[] args)  
  4.     {  
  5.         IWebHostBuilder builder = new WebHostBuilder();  
  6.         builder.ConfigureServices(s =>  
  7.         {  
  8.             s.AddSingleton(builder);  
  9.         });  
  10.         builder.UseKestrel()  
  11.                .UseContentRoot(Directory.GetCurrentDirectory())  
  12.                .UseStartup<Startup>()  
  13.                .UseUrls("http://localhost:9000");  
  14.   
  15.         var host = builder.Build();  
  16.         host.Run();  
  17.     }  
  18. }  

我们还在此处指定API网关的应用URL。

Step 8

运行  API Gateway.

ASP.NET Core

如您所见,我们的API网关在http:// localhost:9000上运行

我们打开浏览器访问我们的服务。

当访问http:// localhost:9000 / api / 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获得结果。

Summary

本文介绍了如何通过Ocelot构建API网关。 希望这个能对您有所帮助!

顺便说一句,这是一个非常简单的演示。 我在本文中没有提到一些重要的事情,例如服务发现,身份验证和服务质量。

原文地址:https://www.c-sharpcorner.com/article/building-api-gateway-using-ocelot-in-asp-net-core/

原文地址:https://www.cnblogs.com/jiangyihz/p/12692479.html