consul ocelot

consul配置完成后

新建.netcoreapi项目,

nuget安装ocelot

添加多个配置文件,.netcore中会自动合并为一个文件,global配置总的配置,其他为各个项目的配置

ServiceName为consul中配置的服务名称:

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/Api/{everything}",
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/Api/{everything}",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "LoadBalancerOptions": {
        //"Type": "RoundRobin",
        "Type": "LeastConnection"
      },
      "ServiceName": "Api",
      "UseServiceDiscovery ": true
    }
  ]
}

配置服务发现:ocelot.global.json

{
  "GlobalConfiguration": {
    "ServiceDiscoveryProvider": {
      "Host": "47.92.80.220",
      "Port": 8500,
      "Type": "Consul"
    }
  }
}

在program.cs中添加json文件,注意AddOcelot

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config
                        .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                        //.AddJsonFile("appsettings.json", true, true)
                        .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                        .AddOcelot( hostingContext.HostingEnvironment)
                        .AddEnvironmentVariables();
                })
                //.UseUrls("http://localhost:1000")
                .UseStartup<Startup>();

在startup.cs的ConfigureServices中注入

services.AddOcelot(Configuration)
                .AddConsul();

在Configure中

app.UseOcelot().Wait();

至此就完成了配置,启动项目后根据配置的路由找到ServiceName,然后会访问服务发现中的路由

posted @ 2019-08-21 11:44  Hey,Coder!  阅读(150)  评论(0编辑  收藏  举报