微服务之网关: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

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