.net core使用ocelot—第一篇 簡單使用

  • 2019 年 10 月 3 日
  • 筆記

簡介原文地址

  接下來你會學習,基於asp.net core 用Ocelot實現一個簡單的API網關。或許你會疑問什麼是API網關,我們先看下面的截圖

  

  API網關是訪問你系統的入口,它包括很多東西,比如路由(Routing),身份驗證(Authentication),服務發現(Service discovery),日誌(Logging ),等等。

Ocelot

     Ocelot提供統一的訪問入口,適用於.net開發的微服務或者開發的面向服務架構,可以訪問Ocelot獲得更多資訊。

     我會用Ocelot實現一個簡單的例子。

Step1

    先創建三個項目,如下所示。

項目名稱

項目類型

描述

APIGateway

ASP.NET Core Empty

Demo的入口

CustomersAPIServices

ASP.NET Core Web API

API Service消費者相關操作

ProductsAPIServices

ASP.NET Core Web API

API Service 產品相關操作

 

 

Step2

     創建兩個API services,在CustimersAPIServices項目中創建CustomersController。

[Route("api/[controller]")]  public class CustomersController : Controller  {      [HttpGet]      public IEnumerable<string> Get()      {          return new string[] { "Catcher Wong", "James Li"     };      }        [HttpGet("{id}")]      public string Get(int id)      {          return $"Catcher Wong - {id}";      }  }  

 

 為了確定CustimersAPIServices的應用URL,我們應該在項目的類中添加UseUrls

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

 

 在PriductsAPIServices項目中新建ProductsController

[Route("api/[controller]")]  public class ProductsController : Controller  {      [HttpGet]      public IEnumerable<string> Get()      {          return new string[] { "Surface Book 2", "Mac Book Pro" };      }  }

 

  

 同樣在項目的類中添加UseUrls

 

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

 

注意

    你可以通過項目的屬性對應用的URL進行配置。

  

Step3

    運行CustimersAPIServices 和ProductsAPIServices。打開兩個cmd終端,cd到兩個服務的文件夾位置,輸入 “dotnet run” 啟動兩個項目。

 運行成功如下所示。

Step4

    接下來我們新建 APIGateway項目,首先安裝Ocelot安裝包。

Install-Package Ocelot

     安裝成功後,如下圖所示。

 

Step5

       在項目下新建configuration.json如下所示。

{      "ReRoutes": [          {              "DownstreamPathTemplate": "/api/customers",              "DownstreamScheme": "http",              "DownstreamHost": "localhost",              "DownstreamPort": 9001,              "UpstreamPathTemplate": "/customers",              "UpstreamHttpMethod": [ "Get" ]          },          {              "DownstreamPathTemplate": "/api/customers/{id}",              "DownstreamScheme": "http",              "DownstreamHost": "localhost",              "DownstreamPort": 9001,              "UpstreamPathTemplate": "/customers/{id}",              "UpstreamHttpMethod": [ "Get" ]          },          {              "DownstreamPathTemplate": "/api/products",              "DownstreamScheme": "http",              "DownstreamPort": 9002,              "DownstreamHost": "localhost",              "UpstreamPathTemplate": "/api/products",              "UpstreamHttpMethod": [ "Get" ]          }      ],      "GlobalConfiguration": {          "RequestIdKey": "OcRequestId",          "AdministrationPath": "/administration"      }  }  

  該文件是API網關的配置文件,包括兩部分,ReRoutes和GlobalConfiguration。

  ReRoutes是告訴Ocelot如何操作上游的request請求,

  GlobalConfiguration有點黑客的感覺,允許對ReRoutes的設置進行重寫。

  用下面的片段介紹ReRoutes。

{      "DownstreamPathTemplate": "/api/customers/{id}",      "DownstreamScheme": "http",      "DownstreamHost": "localhost",      "DownstreamPort": 9001,      "UpstreamPathTemplate": "/customers/{id}",      "UpstreamHttpMethod": [ "Get" ]  }  

 

  以Downstream開頭的項意味我們的請求會指向http://localhost:9001/api/customers/{id}

  以Upstream開頭的項意味我們應該使用/customers/{id} 的HTTP Get請求去訪問服務。

Step6

       修改Startup類,使用Ocelot。

public class Startup  {      public Startup(IHostingEnvironment env)      {          var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();          builder.SetBasePath(env.ContentRootPath)                 //add configuration.json                   .AddJsonFile("configuration.json", optional: false, reloadOnChange: true)                 .AddEnvironmentVariables();            Configuration = builder.Build();      }        //change        public IConfigurationRoot Configuration { get; }        public void ConfigureServices(IServiceCollection services)      {          Action<ConfigurationBuilderCachePart> settings = (x) =>          {              x.WithMicrosoftLogging(log =>              {                  log.AddConsole(LogLevel.Debug);                }).WithDictionaryHandle();          };          services.AddOcelot(Configuration, settings);      }        //don't use Task here        public async void Configure(IApplicationBuilder app, IHostingEnvironment env)      {          await app.UseOcelot();      }  }  

 

  別忘了添加上面的configuration.json文件。

Step7

       這一步至關重要,用來配置Ocelot。

     我們新建IWebHostBuilder的新實例,不要使用var!!!

public class Program  {      public static void Main(string[] args)      {          IWebHostBuilder builder = new WebHostBuilder();          builder.ConfigureServices(s =>          {              s.AddSingleton(builder);          });          builder.UseKestrel()                 .UseContentRoot(Directory.GetCurrentDirectory())                 .UseStartup<Startup>()                 .UseUrls("http://localhost:9000");            var host = builder.Build();          host.Run();      }  }  

  同樣我們需要指明應用的URL。

Step8

     啟動APIGateway,使用cmd通過dotnet run 命令。啟動成功後,輸入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

源碼:APIGatewayDemo

百度網盤

鏈接:https://pan.baidu.com/s/17sqfGcYx8yEHRL_LwKAUlA
提取碼:p3d0

總結

       這篇文章介紹了通過Ocelot創建API網關。希望可以幫到你。

     由於只是簡單的示例程式碼,Ocelot許多重要的特性比如服務發現,身份驗證,服務品質(qos),未在示例中體現。