微服務--Ocelot+Consul整合使用,網關+服務註冊發現

一、爲什麼要有網關Gateway?

1、做服務的管理,屏蔽外界對服務的訪問,保護服務。
2、微服務那麼多服務,而且每一個服務都是集羣式的,調用方不想記住每一個服務的IP+端口號。
3、像授權每一個微服務都要授權,那麼加到網關就可以了。

二、網關是做什麼的?

做請求轉發,映射的,就像一個代理一樣。

三、Ocelot配置

1、nuget引入Ocelot
2、Ocelot配置文件configuration.json

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}",//下游--被調用方--服務地址--url變量
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 10010//服務的端口
        }, //可以多個,自行負載均衡
        {
          "Host": "localhost",
          "Port": 10020//服務的端口
        } //可以多個,自行負載均衡
      ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //輪詢      LeastConnection-最少連接數的服務器   NoLoadBalance不負載均衡
      },
      "UpstreamPathTemplate": "/DavidMeng123456abc/{url}",//上游--調用方--網關地址--url變量   //衝突的還可以加權重Priority
      "UpstreamHttpMethod": [ "Get", "Post" ]
    }
  ]
}

3、Program.cs中替換配置文件configuration.json

namespace NetCore2._2_OcelotGateway
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration(cfg =>
             {
                 cfg.AddJsonFile("configuration.json", optional: false, reloadOnChange: true);
             })
            .UseStartup<Startup>();       
    }
}

4、Startup.cs配置使用Ocelot中間件

namespace NetCore2._2_OcelotGateway
{
    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(Configuration);
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseOcelot().Wait();

            //app.UseHttpsRedirection();
            //app.UseMvc();
        }
    }
}

四、啓動Ocelot Gateway

找到編譯路徑,地址欄輸入cmd,通過命令行啓動

dotnet NetCore2.2_OcelotGateway.dll --urls="http://*:9527" --ip="127.0.0.1" --port=9527

五、通過命令行啓動WebApi

通過命令行啓動2個不同端口的WebApi

dotnet ConsulServiceFind.dll --urls="http://*:10010" --ip="127.0.0.1" --port=10010 --weight=2

dotnet ConsulServiceFind.dll --urls="http://*:10020" --ip="127.0.0.1" --port=10020 --weight=8

六、運行效果

每刷新一次,端口變化一次,完成負載均衡。

七、Gateway缺陷,加個WebApi實例,網關得重啓下,所以需要結合Consul主動服務發現

1、需要在nuget引入Ocelot.Provider.Consul

2、修改Ocelot配置文件configuration.json

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}",//下游--被調用方--服務地址--url變量
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/MyConsul/{url}", //上游--調用方--網關地址--url變量
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "UseServiceDiscovery": true, //使用服務發現
      "ServiceName": "david_webapi", //Consul中註冊的服務名稱
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //輪詢      LeastConnection-最少連接數的服務器   NoLoadBalance不負載均衡
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://127.0.0.1:9527", //網關對外地址
    "ServiceDiscoveryProvider": {//Consul配置
      "Host": "localhost",
      "Port": 8500,
      //由Consul提供服務發現
      "Type": "Consul"
    }
  }
}

3、修改添加中間件

public void ConfigureServices(IServiceCollection services)
{
  services.AddOcelot(Configuration).AddConsul();
  //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

4、再使用命令行啓動一個WebAPi實例,端口號爲10030

 我們看到Consul後臺就主動又發現一個端口號爲10030的服務

 

我們發現第一次頁面打開的時候,端口號爲10010,刷新下頁面,端口號變成了10020,再次刷新頁面,端口號變成了10030,完成了負載均衡,均衡調度。

八、總結Ocelot和Consul區別

1、Ocelot需要維護服務的IP和端口。

2、增加個WebApi實例,configuration.json需要修改,增加配置節點。

3、是維護整個服務的,Consul是維護單個服務的。

 

4、Ocelot是做請求轉發的,而Consul是做服務註冊與發現的,健康檢查的。

九、環境和解決方案截圖

1、環境截圖

啓動了5個控制檯,分別是1個Consul,3個不同端口號的WebApi實例,1個Ocelot Gateway

2、項目截圖

 

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