NetCore3.1項目使用Ocelot與Consul建具備服務注冊和發現功能的網關遇到的坑


創建一個 NetCore3.1的WebAPi項目與NetCore3.1的ServiceGateway網關WebAPI項目

 

 

 

1.服務注冊

在WebAPI項目引用Consul這個包,同時新增ConsulHelper類擴展IConfiguration方法

復制代碼

public static class ConsulHelper
{
  public static void ConsulRegist(this IConfiguration configuration)
  {
    try
    {
      ConsulClient client = new ConsulClient(c =>
      {
        c.Address = new Uri("http://localhost:8500/");
        c.Datacenter = "dc1";
      });
      string ip = configuration["ip"];
      int port = int.Parse(configuration["port"]);//命令行參數必須傳入
      //int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 1 : int.Parse(configuration["weight"]);//命令行參數必須傳入
      client.Agent.ServiceRegister(new AgentServiceRegistration()
      {
        ID = "UserService" + port.ToString(),//唯一的
        Name = "UserService",//組名稱-Group
        Address = ip,//其實應該寫ip地址
        Port = port,//不同實例
        //Tags = new string[] { weight.ToString() },//標簽
        Check = new AgentServiceCheck()//配置心跳檢查的
        {
          Interval = TimeSpan.FromSeconds(12),
          HTTP = $"http://{ip}:{port}/Api/Health/Index",
          Timeout = TimeSpan.FromSeconds(5),
          DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5)
        }
      });
      Console.WriteLine($"http://{ip}:{port}完成注冊");
    }
    catch (Exception ex)
    {
      Console.WriteLine($"ConsulRegist注冊失敗!----異常消息:{ex.Message}");
    }
  }
}

通過這個類可以提供服務注冊的基本參數。

修改Startup啟動項中的Configure方法:

復制代碼
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
  endpoints.MapControllers();
});

Console.WriteLine(this.Configuration["ip"]);
Console.WriteLine(this.Configuration["port"]);
//實例啟動時執行,且只執行一次
this.Configuration.ConsulRegist();

        }
復制代碼

 

2.服務發現

新建API項目ServiceGateway,通過NuGet引用Ocelot和Ocelot.Provider.Consul,Ocelot.Provider.Polly三個包,並修改啟動項注冊Ocelot和Consul:

復制代碼
  public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot().AddConsul().AddPolly();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseOcelot();

            //app.UseMvc();  
        }
復制代碼

然后添加配置文件consul.json:  坑就在這里  ReRoutes 要改成Routes  ,

Ocelot在6.X以后的版本根節點不在使用ReRoutes 更改為Routes 
 
        
 
{
  "Routes": [

{
  "DownstreamPathTemplate": "/api/{url}", //服務地址--url變量
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/consul/{url}", //網關地址--url變量
"UpstreamHttpMethod": [ "Get", "Post" ],
"ServiceName": "UserService", //consul服務名稱
"LoadBalancerOptions": {
"Type": "RoundRobin" //輪詢 LeastConnection-最少連接數的服務器 NoLoadBalance不負載均衡
},
"UseServiceDiscovery": true,
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3, //允許多少個異常請求
"DurationOfBreak": 10000, // 熔斷的時間,單位為ms
"TimeoutValue": 10000 //如果下游請求的處理時間超過多少則自如將請求設置為超時 默認90秒
}
//"RateLimitOptions": {
// "ClientWhitelist": [], //白名單
// "EnableRateLimiting": true,
// "Period": "5m", //1s, 5m, 1h, 1d jeffzhang
// "PeriodTimespan": 5, //多少秒之后客戶端可以重試
// "Limit": 5 //統計時間段內允許的最大請求數量
//},
//"FileCacheOptions": {
// "TtlSeconds": 10
//} //"緩存"
}
],
"GlobalConfiguration": {
"BaseUrl": "http://127.0.0.1:6299", //網關對外地址
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Type": "Consul" //由Consul提供服務發現
}
//"RateLimitOptions": {
// "QuotaExceededMessage": "Too many requests, maybe later? 11", // 當請求過載被截斷時返回的消息
// "HttpStatusCode": 666 // 當請求過載被截斷時返回的http status
//}
}
}

復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM