asp.net core系列 59 Ocelot 構建基礎項目示例


一.入門概述

  從這篇開始探討Ocelot,Ocelot是一個.NET API網關,僅適用於.NET Core,用於.NET面向微服務/服務的架構中。當客戶端(web站點、ios、 app 等)訪問web api時,需要先統一入口點進入Ocelot網關(Ocelot可以做很多事情例如路由,身份驗證,服務發現,日志記錄等,下面列出了功能基本),再由Ocelot分發到web api。Ocelot官方希望IS4一起使用,實現令牌輕松集成。

  Ocelot是一組按特定順序排列的中間件,查看源碼會發現Ocelot是一堆的middleware組成的一個管道。

  Ocelot操控HttpRequest對象到其配置指定的狀態,在中間件中Ocelot創建一個HttpRequestMessage對象,該對象用於向下游服務(wep api)發出請求。發出請求的中間件是Ocelot管道中的最后一件事。它不會調用下一個中間件。

  當下游服務response返回Ocelot管道時,將檢索下游服務的響應。有一個中間件將HttpResponseMessage映射到HttpResponse對象並返回給客戶端。

 

  通過官方部署架構圖介紹,可以了解到:Ocelot有5種部署方式包括:

         (1) Ocelot基本實現

         (2) Ocelot結合IS4、

         (3) Ocelot多個實現(高可用,負載)

         (4) Ocelot結合Consul(健康檢查,服務注冊)、

         (5) Ocelot結合Service Fabric。

  查看部署架構圖,在架構圖中,Ocelot網關暴露在廣域網的一個訪問入口,供客戶端調用。而web api是在局域網中,由Ocelot來轉發。

 

  Ocelot的功能基本包括:

                   路由

                   請求聚合

                   Consul和Eureka的服務發現

                   Service Fabric

                   WebSockets

                   Authentication認證

                   Authorisation授權

                   限速

                   高速緩存

                   重試策略/ QoS

                   負載均衡

                   日志/跟蹤/關聯

                   標頭/查詢字符串/聲明轉換

                   自定義中間件/委托處理程序

                   配置/管理REST API

                   Platform / Cloud Agnostic

 

         安裝Nuget包

                  Install-Package Ocelot

 

二.Ocelot 基礎項目演示

  下面通過貢獻者的開源項目來學習Ocelot,掌握一個基礎項目應用,學習起來也更直觀。示例有三個項目:一個是網關APIGateway項目,有二個是web api服務。 項目實現的功能是:客戶端統一通過網關作為入口點訪問,實現路由的功能。github開源地址   架構如下圖所示:

  

  2.1 CustomersAPIServices項目

    該項目是一個web api項目,用來處理客戶事務的API服務。該地址為http://localhost:9001, 可以在“項目選項”中指定url,也可以在Host啟動時配置。

    (1) Program類添加UseUrls

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                   .UseStartup<Startup>().UseUrls("http://*:9001"); 

    (2)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}";
        }            
    }

 

   2.2 ProductsAPIServices項目 

    該項目是一個web api項目,處理產品某事的API服務。該地址為http://localhost:9002, 可以在“項目選項”中指定url,也可以在Host啟動時配置。

    (1) Program類添加UseUrls

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                   .UseStartup<Startup>().UseUrls("http://*:9002");   

    (2) 在ProductsAPIServices項目中創建ProductsController

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

 

  2.3 APIGateway項目

    該項目是Ocelot網關項目,先安裝Ocelot包。在項目中添加一個Ocelot的json配置文件,這里創建的是configuration.json文件。

    (1) configuration.json(配置Ocelot)

    {
  //ReRoutes:處理上游請求的對象(客戶端),每個數組{} 就是配置:上游地址和對應下游地址
  "ReRoutes": [
    {
      //以Downstream開頭的,是要轉發到下游服務器的地址(CustomersAPIServices),與nginx轉發類似
      //下面所有Downstream開頭的,組成一個轉發url,轉發地址是http://localhost:9001/api/customers
      "DownstreamPathTemplate": "/api/customers",
      "DownstreamScheme": "http",
      // "DownstreamHost": "localhost",
      // "DownstreamPort": 9001,
      //轉發到下游服務器的主機和端口。
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9001
        }
      ],
      //Upstream開頭是指上游服務器(客戶端)訪問地址,通過http get方式訪問。
      //也就是說客戶端訪問http://localhost:9000/customers 實際是轉發到了http://localhost:9001/api/customers的服務
      "UpstreamPathTemplate": "/customers",
      "UpstreamHttpMethod": [ "Get" ]
    },
    {
      "DownstreamPathTemplate": "/api/customers/{id}",
      "DownstreamScheme": "http",
      // "DownstreamHost": "localhost",
      // "DownstreamPort": 9001,
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9001
        }
      ],
      "UpstreamPathTemplate": "/customers/{id}",
      "UpstreamHttpMethod": [ "Get" ]
    },
    {
      "DownstreamPathTemplate": "/api/products",
      "DownstreamScheme": "http",
      // "DownstreamPort": 9002,
      // "DownstreamHost": "localhost",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9002
        }
      ],
      "UpstreamPathTemplate": "/api/products",
      "UpstreamHttpMethod": [ "Get" ]
    }
  ],
  //全局配置,允許覆蓋ReRoutes特定設置
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/administration"
  }
}

    (2) Startup類,使用Ocelot

          public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                   //.UseStartup<Startup>()
                //設置網關url
                   .UseUrls("http://*:9000")
                   .ConfigureAppConfiguration((hostingContext, config) =>
               {
                   config
                       .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                    //添加Ocelot配置文件
                       .AddJsonFile("configuration.json")
                       .AddEnvironmentVariables();
               })
               .ConfigureServices(s =>
               {
                //添加服務
                   s.AddOcelot();
                   s.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
               })
                .Configure(a =>
                {        
                //添加中間件            
                    a.UseOcelot().Wait();
                });

    

  最后開始測試:

    (1) 啟動CustomersAPIServices web api服務程序 http://localhost:9001

    (2) 啟動ProductsAPIServices web api服務程序  http://localhost:9002

    (3) 啟動 APIGateway 網關服務程序  http://localhost:9000

    

 

三. 關於ReRoutes路由介紹

  在上面示例中,使用了基本的路由配置,在ocelot路由配置中,還有許多特性,比如:   

  (1) 給DownstreamPathTemplate和UpstreamPathTemplate設置占位符,來捕捉所有類型的ReRoute,是使用直接代理。

  (2) 設置上游(客戶端)的主機頭來匹配 "UpstreamHost": "somedomain.com"。

  (3) 設置路由的優先級,Priority的數字越高代表級別越高。

  (4) 設置動態路由,不必提供ReRoute配置。

  (5) 設置查詢字符串,根據url的參數unitId={unitId}來匹配轉發。

  

 

參考文獻

  構建基礎Ocelot項目介紹

   官方文檔

  

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM