.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:

 


免責聲明!

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



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