Asp.Net Core + Ocelot 閘道器搭建:路由簡單配置

丶Pz發表於2018-10-19

前言

  Ocelot是一個基於中介軟體的閘道器實現,功能有很多。從淺入深簡單學習並記錄一下吧。本篇就是一個簡單的路由配置實現。

DEMO 搭建

  首先建立三個專案。Api.User,Api.Article,Api.GateWay.ApiGateWay專案中引入Ocelot Nuget包.新增配置檔案Ocelot.json.

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/{all}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 60001
        }
      ],
      "UpstreamPathTemplate": "/user/{all}",
      "UpstreamHttpMethod": ["GET","POST"]
    },
    {
      "DownstreamPathTemplate": "/{all}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 60002
        }
      ],
      "UpstreamPathTemplate": "/article/{all}",
      "UpstreamHttpMethod": ["GET","POST"]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:60003/"
  }
}

  啟動的時候將配置檔案加進去,並且Startup中新增相應的中介軟體:services.AddOcelot(),app.UseOcelot();

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration((hostingContext, config) =>
             {
                 config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                       .AddJsonFile("ocelot.json", optional: true, reloadOnChange: true)
                       .AddEnvironmentVariables();
             }).UseStartup<Startup>();

  啟動三個專案,執行效果如下:
Asp.Net Core + Ocelot 閘道器搭建:路由簡單配置

總結

  這樣就能實現將閘道器做為統一入口,統一管理了。後續在加上各種Ocelot的功能實現。

相關文章