Asp.Net?Core使用Ocelot結(jié)合Consul實現(xiàn)服務(wù)注冊和發(fā)現(xiàn)
1.服務(wù)注冊與發(fā)現(xiàn)(Service Discovery)
- 服務(wù)注冊:我們通過在每個服務(wù)實例寫入注冊代碼,實例在啟動的時候會先去注冊中心(例如Consul、ZooKeeper、etcd、Eureka)注冊一下,那么客戶端通過注冊中心可以知道每個服務(wù)實例的地址,端口號,健康狀態(tài)等等信息,也可以通過注冊中心刪除服務(wù)實例。這里注冊中心相當于是負責維護服務(wù)實例的管控中心。
- 服務(wù)發(fā)現(xiàn):服務(wù)實例在注冊中心注冊之后,客戶端通過注冊中心可以了解這些服務(wù)實例運行狀況。
2.Consul
如果要實現(xiàn)服務(wù)注冊與發(fā)現(xiàn),需要一個注冊中心,這里主要介紹是Consul。
Consul官網(wǎng):https://www.consul.io/,它主要功能有:服務(wù)注冊與發(fā)現(xiàn)、健康檢查、Key/Value、多數(shù)據(jù)中心。
如果在Windows上部署Consul,在consul.exe目錄下執(zhí)行consul.exe agent -dev命令行即可。
3.Asp.Net Core向Consul注冊服務(wù)實例
Asp.Net Core向Consul注冊服務(wù)實例調(diào)用過程如下圖所示:

Asp.Net Core向Consul注冊服務(wù)實例需要在Gateway項目中引用Consul支持的NuGet軟件包,安裝命令如下:
Install-Package Ocelot.Provider.Consul
然后將以下內(nèi)容添加到您的ConfigureServices方法中:
services.AddOcelot().AddConsul();
在Ocelot服務(wù)發(fā)現(xiàn)項目示例中,通過APIGateway項目GlobalConfiguration選項可以配置服務(wù)注冊與發(fā)現(xiàn),文件配置具體代碼如下:
{
"Routes": [
{
"UseServiceDiscovery": true,
"DownstreamPathTemplate": "/{url}",
"DownstreamScheme": "http",
"ServiceName": "MyService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"UpstreamPathTemplate": "/{url}",
"UpstreamHttpMethod": [ "Get" ],
"ReRoutesCaseSensitive": false
}
],
"GlobalConfiguration": {
//服務(wù)發(fā)現(xiàn)配置
"ServiceDiscoveryProvider": {
//注冊中心Consul地址
"Host": "192.168.113.128",
//注冊中心Consul端口號
"Port": 8500,
"Type": "Consul",
//以毫秒為單位,告訴Ocelot多久調(diào)用一次Consul來更改服務(wù)配置。
"PollingInterval": 100,
//如果你有在Consul上配置key/value,則在這里輸入配置key。
"ConfigurationKey": "MyService_AB"
}
}
}ServiceDiscoveryProvider選項說明:
- Host:注冊中心Consul地址。
- Port:注冊中心Consul端口號。
- Type:注冊中心類型。
- PollingInterval:以毫秒為單位,告訴Ocelot多久調(diào)用一次Consul來更改服務(wù)配置。
- ConfigurationKey:如果你有在Consul上配置key/value,則在這里輸入配置key。
4.項目演示
4.1APIGateway項目
ConfigureServices添加Ocelot、Consul注入:
services.AddOcelot().AddConsul();
Configure添加使用Ocelot:
app.UseOcelot().Wait();
服務(wù)發(fā)現(xiàn)配置如Ocelot服務(wù)發(fā)現(xiàn)項目示例一樣。
4.2Common項目
先安裝Consul的NuGet軟件包,安裝命令如下:
Install-Package Consul
在該項目添加一個AppExtensions擴展類,用來對服務(wù)APIServiceA、APIServiceB項目在Consul注冊實例,為了展示效果,具體代碼稍作修改如下:
public static class AppExtensions
{
public static IServiceCollection AddConsulConfig(this IServiceCollection services, IConfiguration configuration)
{
services.AddSingleton<IConsulClient, ConsulClient>(p => new ConsulClient(consulConfig =>
{
var address = configuration.GetValue<string>("Consul:Host");
consulConfig.Address = new Uri(address);
}));
return services;
}
public static IApplicationBuilder UseConsul(this IApplicationBuilder app, string host = null, string port = null)
{
//獲取consul客戶端實例
var consulClient = app.ApplicationServices.GetRequiredService<IConsulClient>();
var logger = app.ApplicationServices.GetRequiredService<ILoggerFactory>().CreateLogger("AppExtensions");
var lifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
if (!(app.Properties["server.Features"] is FeatureCollection features)) return app;
//var addresses = features.Get<IServerAddressesFeature>();
//var address = addresses.Addresses.FirstOrDefault();
//if (address == null)
//{
// return app;
//}
var address = host + ":" + port;
if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(port))
{
Console.WriteLine($"host或者port為空!");
return app;
}
Console.WriteLine($"address={address}");
var uri = new Uri(address);
Console.WriteLine($"host={uri.Host},port={uri.Port}");
var registration = new AgentServiceRegistration()
{
ID = $"MyService-{uri.Port}",
Name = "MyService",
Address = $"{uri.Host}",
Port = uri.Port,
Check = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服務(wù)啟動多久后注冊
Interval = TimeSpan.FromSeconds(10),//健康檢查時間間隔
HTTP = $"{address}/HealthCheck",//健康檢查地址
Timeout = TimeSpan.FromSeconds(5)//超時時間
}
};
logger.LogInformation("Registering with Consul");
logger.LogInformation($"Consul RegistrationID:{registration.ID}");
//注銷
consulClient.Agent.ServiceDeregister(registration.ID).ConfigureAwait(true);
//注冊
consulClient.Agent.ServiceRegister(registration).ConfigureAwait(true);
//應(yīng)用程序關(guān)閉時候
lifetime.ApplicationStopping.Register(() =>
{
//正在注銷
logger.LogInformation("Unregistering from Consul");
consulClient.Agent.ServiceDeregister(registration.ID).ConfigureAwait(true);
});
//每個服務(wù)都需要提供一個用于健康檢查的接口,該接口不具備業(yè)務(wù)功能。服務(wù)注冊時把這個接口的地址也告訴注冊中心,注冊中心會定時調(diào)用這個接口來檢測服務(wù)是否正常,如果不正常,則將它移除,這樣就保證了服務(wù)的可用性。
app.Map("/HealthCheck", s =>
{
s.Run(async context =>
{
await context.Response.WriteAsync("ok");
});
});
return app;
}
}4.3APIServiceA項目
項目添加一個Get方法,對應(yīng)APIGateway項目的路由上下游配置,具體代碼如下:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
var port = Request.Host.Port;
return new string[] { "value1", "value2", port.Value.ToString() };
}
}appsettings.json配置加入Consul地址:
"Consul": {
"Host": "http://192.168.113.128:8500"
}4.4APIServiceB項目
項目添加一個Get方法,對應(yīng)APIGateway項目的路由上下游配置,具體代碼如下:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
var port = Request.Host.Port;
return new string[] { "value3", "value4", port.Value.ToString() };
}
}appsettings.json配置加入Consul地址:
"Consul": {
"Host": "http://192.168.113.128:8500"
}4.5項目運行
在APIServiceA、APIServiceB項目的ConfigureServices添加Consul配置:
services.AddConsulConfig(Configuration);
在Configure添加Consul服務(wù)注冊:
APIServiceA:app.UseConsul("http://172.168.18.73", "9999");
APIServiceB:app.UseConsul("http://172.168.18.73", "9998");把APIGateway、APIServiceA、APIServiceB三個項目部署到IIS上:

三個項目運行起來后,通過瀏覽器Consul客戶端可以看到MyService節(jié)點服務(wù)情況:

點擊打開MyService節(jié)點可以看到注冊到Consul的APIServiceA、APIServiceB服務(wù)狀況:

如果把APIServiceB服務(wù)實例站點停掉:

通過Consul客戶端會看到APIServiceB服務(wù)實例已經(jīng)被剔除了:

如果輸入CTRL+C把集群中某一個Consul服務(wù)關(guān)閉,那么集群會重新選舉一個新的leader,負責處理所有服務(wù)實例的查詢和事務(wù):


到此這篇關(guān)于Asp.Net Core使用Ocelot結(jié)合Consul實現(xiàn)服務(wù)注冊和發(fā)現(xiàn)的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
this connector is disabled錯誤的解決方法
打開editor/filemanager/connectors/aspx/config.ascx修改CheckAuthentication()方法,返回true2008-11-11
.net生成縮略圖及水印圖片時出現(xiàn)GDI+中發(fā)生一般性錯誤解決方法
這篇文章主要介紹了.net生成縮略圖及水印圖片時出現(xiàn)GDI+中發(fā)生一般性錯誤解決方法 ,需要的朋友可以參考下2014-11-11
ASP.NET Core 數(shù)據(jù)保護(Data Protection)中篇
這篇文章主要為大家再一次介紹了ASP.NET Core 數(shù)據(jù)保護(Data Protection),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09
利用ASP.NET MVC+Bootstrap搭建個人博客之praise.js點贊特效插件(二)
這篇文章主要介紹了利用ASP.NET和MVC+Bootstrap搭建個人博客之praise.js點贊特效插件(二)的相關(guān)資料,需要的朋友可以參考下2016-06-06

