赞
踩
分布式结构,应用服务就不能是单个应用,必须得提供多个,相当于是这个服务的集群(单独一个服务坏了,不影响其他服务继续提供服务)。
那么基于这个应用服务的集群管理,就是服务注册与发现服务。
它主要是用来管理你的应用服务集群的。
实际情况中,你的服务会部署在Docker容器中,然后,它在容器里向外暴漏自己的位置,告诉 服务注册与发现,我在这里,我要报名,我要为客户提供服务。
然后,服务中心会管理这些注册上来的服务,并会定时检查它们是否存在,如果不存在,就给它们下线,不让他们继续服务了。
如上图,实现服务注册与发现,可以通过 Consul、Zookeeper、Etcd 技术实现,Zookeeper 是 kafka 集群的时候用到的技术组件。
我这里主要介绍 Consul 这个组件 (谷歌出品,Go语言开发),内置服务注册与发现、配置服务中心,健康检查、一致性协议(选举协议),服务部署简单。
可以根据我这篇文章来对服务进行部署(集群高可用)等方式。
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>();
- });
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
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();
- });
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
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 });
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
以及项目启动的命令信息如下:
- 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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。