1. 程式人生 > >.NET Core 微服務—API閘道器(Ocelot) 教程 [二]

.NET Core 微服務—API閘道器(Ocelot) 教程 [二]

上篇文章(.NET Core 微服務—API閘道器(Ocelot) 教程 [一])介紹了Ocelot 的相關介紹。

接下來就一起來看如何使用,讓它執行起來。

環境準備

  為了驗證Ocelot 閘道器效果,我們先建立3個webapi專案:目錄api(Api.Catalog)、訂單api(Api.Ordering)、Ocelot閘道器(ApiGateway.Ocelot);併為每個WebApi專案新增Values控制器(ValuesController),用於區分最終呼叫效果

  如下圖:

   

Ocelot使用

  1、新增Ocelot包依賴:

  接下來使用Nuget包管理工具為ApiGateway.Ocelot專案新增Ocelot包引用:

  

    當然也可用使用命令方式新增Ocelot包:

Install-Package Ocelot

  2、新增Ocelot配置檔案:(重點)

    向ApiGateway.Ocelot專案新增一個Ocelot.json配置檔案,並修改配置檔案為如下內容: 

{
  "GlobalConfiguration": {

  },
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5331
        },
        {
          "Host": "localhost",
          "Port": 5332
        }
      ],
      "UpstreamPathTemplate": "/{everything}",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      }
    }
  ]
}
View Code

     接下來簡單介紹下相關配置節點意義。可以看出配置檔案主要包含:Routes和GlobalConfiguration。完整的配置內容可以檢視:官方文件 

GlobalConfiguration:顧名思義就是全域性配置,此節點的配置允許覆蓋Routes裡面的配置
Routes:告訴Ocelot如何處理上游的請求
  DownstreamPathTemplate:下游的路由模板,即真實處理請求的路徑模板
  DownstreamScheme:請求的方式,如:http,https
  DownstreamHostAndPorts:下游的IP以及埠,可以有多個(如果使用負載均衡),方便實現負載均衡,當然你也可以使用服務發現,實現下游服務的自動註冊與發現
  UpstreamPathTemplate:上游請求的模板,即使用者真實請求的連結
  UpstreamHttpMethod:上游請求的http方法,是個陣列,你可以寫多個
  LoadBalancerOptions:負載均衡選項(DownstreamHostAndPorts有多個的時候才能看到效果),有三種方式
    LeastConnection : 將請求發往最空閒的那個伺服器
    RoundRobin :輪流傳送
    NoLoadBalance :不啟用負載均衡,總是發往第一個請求或者服務發現的那個伺服器

  3、啟用Ocelot中介軟體:

    a) 首先在ApiGateway.Ocelot專案中的Program.cs中載入ocelot.json的配置檔案,如下所示:

 public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                        .AddJsonFile("appsettings.json", true, true)
                        .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                        .AddJsonFile("ocelot.json")
                        .AddEnvironmentVariables();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
View Code

    b) 接下來在Startup.cs檔案中註冊服務:

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot();//注入Ocelot服務

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseOcelot().Wait();//使用Ocelot中介軟體

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
View Code

    c) 最後:

      把目錄api(Api.Catalog)、訂單api(Api.Ordering)、Ocelot閘道器(ApiGateway.Ocelot)分別設定啟動設定為:http://localhost:5332、http://localhost:5331、http://localhost:5330。

      到此Ocelot基本使用完成,接下來驗證下效果

效果驗證:

  通過ocelot.json設定可以得到:

  • Ocelot閘道器設定生效,上游路由模板"/{everything}"對應下游路由模板"/api/{everything}"(也就是通過http://localhost:5330/values訪問,最終訪問的是http://localhost:5331/api/values或http://localhost:5332/api/values)
  • 負載均衡選項設定的是:輪詢(http://localhost:5330/values訪問,重新整理後兩次結果不相同)

  接著驗證執行效果是不是這樣:

  1、開啟http://localhost:5330/values 如下圖:最終得到是: Api.Catalog 的結果

 

   

 

 

   2、接著我們重新整理下當前介面:得到如下結果:負載均衡輪詢選項生效成功

   

 總結:

  通過上面的示例,非常簡單的就成功的運行了Ocelot閘道器的路由效果和負載均衡的簡單效果。

   接下來我就要進一步詳細瞭解Ocelot的配置內容和其他使用方式(如:認證服務方式、服務自動發現註冊)

 

 Reference:

  • https://github.com/ThreeMammals/Ocelot
  • https://ocelot.readthedocs.io/en/latest/features/configuration.html

&n