微服務之網關:Ocelot+Consul實現動態集羣擴展

1、作用與目的

實現使用統一網關來訪問不同的地址,以便我們以後實現微服務的分發部署,雖然是多個接口來實現的,但是我們給上游訪問還是提供一個接口,我們內部實現訪問該訪問那個接口。

Ocelot允許您指定服務發現提供程序,並使用它來查找Ocelot正在將請求轉發給下游服務的主機和端口。

所以我們可以結合Ocelot與Consul進行聯合實現動態集羣擴展。

2、代碼配置

2.1 創建空項目並添加 Ocelot支持

 Install-Package Ocelot

 

2.2添加一個json配置文件

{
  "ReRoutes": [],
  "GlobalConfiguration": {
    "BaseUrl": "http:127.0.0.1:8888/"//該地址是當前網關程序的運行地址
  }
}

 2.3生效配置文件

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

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).ConfigureAppConfiguration(builder =>
                {
                    //增加配置文件
                    builder.AddJsonFile("ocelot.json");
                });
    }

 

2.4 設置服務和中間件

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot();//添加Ocelot服務
        }

        // 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.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
    }

 3、網關靜態轉發

3.1修改配置文件

{
  //15版本及之前爲ReRoutes
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/Users/GetUser?id={id}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "127.0.0.1",
          "Port": 5211
        }
      ],
      "UpstreamPathTemplate": "/Users/Get?id={id}",
      "UpstreamHttpMethod": [ "Get", "Delete" ]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http:127.0.0.1:8888/" //該地址是當前網關程序的運行地址
  }
}

 

配置文件解釋:

該配置文件實現了將請求:http://127.0.0.1:8888/Users/get?id=1 轉發到:http://127.0.0.1:5211/api/Users/getuser?id=1的效果。

實際的接口地址是後者,前者是網關地址。起到了隱藏真實接口地址的效果。

 

4、實現多個接口輪詢

 

 

修改配置文件如下:

{
  //15版本及之前節點名稱爲ReRoutes
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/Users/GetUser?id={id}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "127.0.0.1",
          "Port": 5210
        },
        {
          "Host": "127.0.0.1",
          "Port": 5211
        },
        {
          "Host": "127.0.0.1",
          "Port": 5212
        }
      ],
      "UpstreamPathTemplate": "/Users/Get?id={id}",
      "UpstreamHttpMethod": [ "Get", "Delete" ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http:127.0.0.1:8888/" //該地址是當前網關程序的運行地址
  }
}

 

5、配合consul(服務註冊發現)實現動態控制

實現效果:如果需要新增服務的時候,不用修改靜態配置文件。ocelot自動獲取consul發現的所有服務,實現集羣功能。

5.1添加引用

 

5.2修改服務註冊

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot().AddConsul();//添加Ocelot服務
        }

 

5.3修改配置文件:

{
  //15版本及之前爲ReRoutes
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/Users/GetUser?id={id}",
      "DownstreamScheme": "http",
      //"DownstreamHostAndPorts": [
      //  {
      //    "Host": "127.0.0.1",
      //    "Port": 5210
      //  },
      //  {
      //    "Host": "127.0.0.1",
      //    "Port": 5211
      //  },
      //  {
      //    "Host": "127.0.0.1",
      //    "Port": 5212
      //  }
      //],
      "UpstreamPathTemplate": "/Users/Get?id={id}",
      "UpstreamHttpMethod": [ "Get", "Delete" ],
      "ServiceName": "BaseDataServer",
      "UseServiceDiscovery": true,
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      }
    }
  ],
  "GlobalConfiguration": {
    //"BaseUrl": "http:127.0.0.1:8888/" //該地址是當前網關程序的運行地址
    "ServiceDiscoveryProvider": {
      "Host": "localhost",
      "Port": 8500,
      "Type": "PollConsul",
      "PollingInterval": 100
    }
  }
}

 

Ocelot允許您指定服務發現提供程序,並使用它來查找Ocelot正在將請求轉發給下游服務的主機和端口。目前,這僅在GlobalConfiguration部分中受支持,這意味着將爲所有的ReRoute使用相同的服務發現提供程序,以便在ReRoute級別指定ServiceName。

  • ServiceName:consul的服務名稱
  • LoadBalancerOptions:使用的算法,目前有兩種RoundRobin(輪詢方式)和LeastConnection(最小連接)
  • UseServiceDiscovery:是否啓用服務發現功能 true:爲啓動
  • ServiceDiscoveryProvider:配置服務發現的一些配置
  • Host:主機地址
  • Port:端口
  • PollingInterval:輪詢的間隔時間,以毫秒爲單位。並告訴Ocelot多久可以向Consul調用服務配置的更改

想要了解更多可以訪問Ocelot官網:http://ocelot.readthedocs.io/en/latest/features/servicediscovery.html

到此配置完畢,這樣我們想要在集羣中新增接口時候,直接啓動服務實例後就可以被consul發現,進而被ocelot網關自動轉發了。

6最終效果:

6.1新增加一個服務實例:

dotnet MicroService.dll --urls="http://*:5213" --ip="127.0.0.1" --port 5213

 

6.2consul自動發現

 

 6.3網關自動轉發

 

 需要查看consul的配置方法請看:https://www.cnblogs.com/chenxizhaolu/p/13890309.html

參考:https://www.cnblogs.com/yanbigfeg/p/9228419.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章