.net core後端webapi註冊到consul,並通過網關訪問

步驟1:為項目添加consul依賴

步驟2:在項目中配置consul,具體如下

配置文件中添加如下

"Service": {

 

"Name": "homepage",

 

"IP": "172.17.0.12",

 

"Port": "8300"

 

},

 

"Consul": {

 

"IP": "172.17.0.12",

 

"Port": "8500"

 

}

補全startup.cs中的如下方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)

{

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

app.UseCors(x => x

.AllowAnyOrigin()

.AllowAnyMethod()

.AllowAnyHeader()

.AllowCredentials());

#region register this service

 

ConsulService consulService = new ConsulService()

 

{

 

IP = Configuration["Consul:IP"],

 

Port = Convert.ToInt32(Configuration["Consul:Port"])

 

};

 

HealthService healthService = new HealthService()

 

{

 

IP = Configuration["Service:IP"],

 

Port = Convert.ToInt32(Configuration["Service:Port"]),

 

Name = Configuration["Service:Name"],

 

};

 

app.RegisterConsul(lifetime, healthService, consulService);

#endregion

app.UseMvc();

}

添加三個類:

consul註冊類:

using Consul;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.Extensions.Options;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

 

namespace MaskBackground.Extensions

{

public static class ConsulBuilderExtensions

 

{

 

// 服務註冊

 

public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, HealthService healthService, ConsulService consulService)

 

{

 

var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{consulService.IP}:{consulService.Port}"));//請求註冊的 Consul 地址

 

var httpCheck = new AgentServiceCheck()

 

{

 

DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服務啓動多久後註冊

 

Interval = TimeSpan.FromSeconds(10),//健康檢查時間間隔,或者稱爲心跳間隔

//HTTP = "http://61.174.171.58:5556/api/health/status",

HTTP = $"http://{healthService.IP}:{healthService.Port}/api/health/status",//健康檢查地址

 

Timeout = TimeSpan.FromSeconds(5)

 

};

 

// Register service with consul

 

var registration = new AgentServiceRegistration()

 

{

 

Checks = new[] { httpCheck },

 

ID = healthService.Name + "_" + healthService.Port,

 

Name = healthService.Name,

 

Address = healthService.IP,

 

Port = healthService.Port,

 

Tags = new[] { $"urlprefix-/{healthService.Name}" }//添加 urlprefix-/servicename 格式的 tag 標籤,以便 Fabio 識別

 

};

 

consulClient.Agent.ServiceRegister(registration).Wait();//服務啓動時註冊,內部實現其實就是使用 Consul API 進行註冊(HttpClient發起)

 

lifetime.ApplicationStopping.Register(() =>

 

{

 

consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服務停止時取消註冊

 

});

 

return app;

 

}

 

}

 

 

}

 

參數類:

 

namespace MaskBackground.Extensions

{

public class ConsulService

 

{

 

public string IP { get; set; }

 

public int Port { get; set; }

 

}

}

namespace MaskBackground.Extensions

{

public class HealthService

 

{

 

public string Name { get; set; }

 

public string IP { get; set; }

 

public int Port { get; set; }

 

 

 

}

}

心跳檢測方法

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

 

namespace HomeBg.Controllers

{

[Route("api/[controller]")]

[ApiController]

public class HealthController : ControllerBase

{

[AllowAnonymous]

[HttpGet("status")]

public IActionResult Status() => Ok(new {Message = $"OK",DateTime = DateTime.Now});

}

}

步驟3:在項目主配置文件中配置網關

 

 

"ReRouteOptions": {

"DownstreamPathTemplate": "/api/{url}",

"UpstreamPathTemplate": "/api/homepage/{url}",

"ServiceName": "homepage",

"UseServiceDiscovery": true,

"DownstreamScheme": "http",

"UpstreamHttpMethod": [ "Get", "Post" ],

"LoadBalancer": "LeastConnection",

"ReRouteIsCaseSensitive": false,

"Priority": 9

}

步驟4:在consul中建立網關鍵值對

 

reroutes-後面的為註冊到consul的服務名稱。寫入如下配置。

 

[{"DownstreamPathTemplate":"/api/{url}","DownstreamScheme":"http","UpstreamPathTemplate":"/api/homepage/{url}","UpstreamHttpMethod":["Get","Post"],"ServiceName":"homepage","LoadBalancer":"LeastConnection","UseServiceDiscovery":true,"ReRouteIsCaseSensitive":false,"Priority":9}]

步驟5:重啓網關

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