分布式結構,應用服務就不能是單個應用,必須得提供多個,相當于是這個服務的叢集(單獨一個服務壞了,不影響其他服務繼續提供服務)。
那麼基于這個應用服務的叢集管理,就是服務注冊與發現服務。
它主要是用來管理你的應用服務叢集的。
實際情況中,你的服務會部署在Docker容器中,然後,它在容器裡向外暴漏自己的位置,告訴 服務注冊與發現,我在這裡,我要報名,我要為客戶提供服務。
然後,服務中心會管理這些注冊上來的服務,并會定時檢查它們是否存在,如果不存在,就給它們下線,不讓他們繼續服務了。
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIwczX0xiRGZkRGZ0Xy9GbvNGL2EzXlpXazxSPrdlWv50MjxGdywEMW1mY1RzRapnTtxkb5ckYplTeMZTTINGMShUYfRHelRHLwEzX39GZhh2css2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xyayFWbyVGdhd3LcV2Zh1Wa9M3clN2byBXLzN3btg3Pn5GcuQjM5IDM0cTM0EzMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
如上圖,實作服務注冊與發現,可以通過 Consul、Zookeeper、Etcd 技術實作,Zookeeper 是 kafka 叢集的時候用到的技術元件。
我這裡主要介紹 Consul 這個元件 (谷歌出品,Go語言開發),内置服務注冊與發現、配置服務中心,健康檢查、一緻性協定(選舉協定),服務部署簡單。
可以根據我這篇文章來對服務進行部署(叢集高可用)等方式。
Consul元件 安裝與部署 (window),叢集部署,并驗證其高可用
https://blog.csdn.net/i2blue/article/details/114797809
部署完整以後,就需要在具體的服務中使用。
這個時候,就需要開發一個服務進行連接配接
就建立一個.Net5.0的項目,然後 結構如下,主要修改了以下三個地方。
Program (增加了識别指令行資訊)
public class Program
{
public static void Main(string[] args)
{
new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddCommandLine(args)//支援指令行參數
.Build();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Startup (增加了指令參數資訊擷取和Consul 服務注冊,以及服務停止時撤銷注冊的服務資訊)
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.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
ConsulRegist(Configuration, lifetime);
}
public void ConsulRegist(IConfiguration configuration, IHostApplicationLifetime lifetime)
{
ConsulClient client = new ConsulClient(c =>
{
c.Address = new Uri("http://192.168.2.7:8500/");
c.Datacenter = "dc1";
});
string ip = configuration["ip"];
int port = int.Parse(configuration["port"]);
string serverName = configuration["name"];
var registration = new AgentServiceRegistration()
{
ID = serverName + Guid.NewGuid(),
Name = serverName,
Address = ip,
Port = port,
Tags = new string[] { },
Check = new AgentServiceCheck()
{
Interval = TimeSpan.FromSeconds(12),
HTTP = $"http://{ip}:{port}/Home/Health",
Timeout = TimeSpan.FromSeconds(5),
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)
}
};
client.Agent.ServiceRegister(registration);
// 應用程式終止時,服務取消注冊
lifetime.ApplicationStopping.Register(() =>
{
client.Agent.ServiceDeregister(registration.ID).Wait();
});
}
}
HomeController (主要增加了 健康檢查 Health和Consul服務的擷取)
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
ConsulClient client = new ConsulClient(c =>
{
c.Address = new Uri("http://192.168.2.7:8500/");
c.Datacenter = "dc1";
});
return Json(client.Agent.Services().Result.Response);
}
public IActionResult Health()
{
return Ok();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
以及項目啟動的指令資訊如下:
dotnet Server.dll --urls http://192.168.1.6:1000 --ip 192.168.1.6 --port 1000 --name server1
dotnet Server.dll --urls http://192.168.1.6:1001 --ip 192.168.1.6 --port 1001 --name server2
最後,結果如下
已經注冊到Consul上兩個服務了。
通路位址,也能傳回相應的服務資訊。
至此,服務的注冊與發現已經完成。可以根據業務需要來搭建架構。
Demo下載下傳位址: https://download.csdn.net/download/kesshei/15805492