当前位置:   article > 正文

.Net5.0 微服务之服务注册与发现(Consul)_netcroe 5.0.17怎么注册

netcroe 5.0.17怎么注册

分布式结构,应用服务就不能是单个应用,必须得提供多个,相当于是这个服务的集群(单独一个服务坏了,不影响其他服务继续提供服务)。

那么基于这个应用服务的集群管理,就是服务注册与发现服务。

它主要是用来管理你的应用服务集群的。

实际情况中,你的服务会部署在Docker容器中,然后,它在容器里向外暴漏自己的位置,告诉 服务注册与发现,我在这里,我要报名,我要为客户提供服务。

然后,服务中心会管理这些注册上来的服务,并会定时检查它们是否存在,如果不存在,就给它们下线,不让他们继续服务了。

如上图,实现服务注册与发现,可以通过 Consul、Zookeeper、Etcd 技术实现,Zookeeper 是 kafka 集群的时候用到的技术组件。

我这里主要介绍  Consul 这个组件 (谷歌出品,Go语言开发),内置服务注册与发现、配置服务中心,健康检查、一致性协议(选举协议),服务部署简单。

可以根据我这篇文章来对服务进行部署(集群高可用)等方式。

Consul组件 安装与部署 (window),集群部署,并验证其高可用

https://blog.csdn.net/i2blue/article/details/114797809

部署完整以后,就需要在具体的服务中使用。

这个时候,就需要开发一个服务进行连接

就新建一个.Net5.0的项目,然后 结构如下,主要修改了以下三个地方。

Program  (增加了识别命令行信息)

  1. public class Program
  2. {
  3. public static void Main(string[] args)
  4. {
  5. new ConfigurationBuilder()
  6. .SetBasePath(Directory.GetCurrentDirectory())
  7. .AddCommandLine(args)//支持命令行参数
  8. .Build();
  9. CreateHostBuilder(args).Build().Run();
  10. }
  11. public static IHostBuilder CreateHostBuilder(string[] args) =>
  12. Host.CreateDefaultBuilder(args)
  13. .ConfigureWebHostDefaults(webBuilder =>
  14. {
  15. webBuilder.UseStartup<Startup>();
  16. });
  17. }

Startup (增加了命令参数信息获取和Consul 服务注册,以及服务停止时撤销注册的服务信息)

  1. public class Startup
  2. {
  3. public Startup(IConfiguration configuration)
  4. {
  5. Configuration = configuration;
  6. }
  7. public IConfiguration Configuration { get; }
  8. // This method gets called by the runtime. Use this method to add services to the container.
  9. public void ConfigureServices(IServiceCollection services)
  10. {
  11. services.AddControllersWithViews();
  12. }
  13. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  14. public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime, IWebHostEnvironment env)
  15. {
  16. if (env.IsDevelopment())
  17. {
  18. app.UseDeveloperExceptionPage();
  19. }
  20. else
  21. {
  22. app.UseExceptionHandler("/Home/Error");
  23. }
  24. app.UseStaticFiles();
  25. app.UseRouting();
  26. app.UseAuthorization();
  27. app.UseEndpoints(endpoints =>
  28. {
  29. endpoints.MapControllerRoute(
  30. name: "default",
  31. pattern: "{controller=Home}/{action=Index}/{id?}");
  32. });
  33. ConsulRegist(Configuration, lifetime);
  34. }
  35. public void ConsulRegist(IConfiguration configuration, IHostApplicationLifetime lifetime)
  36. {
  37. ConsulClient client = new ConsulClient(c =>
  38. {
  39. c.Address = new Uri("http://192.168.2.7:8500/");
  40. c.Datacenter = "dc1";
  41. });
  42. string ip = configuration["ip"];
  43. int port = int.Parse(configuration["port"]);
  44. string serverName = configuration["name"];
  45. var registration = new AgentServiceRegistration()
  46. {
  47. ID = serverName + Guid.NewGuid(),
  48. Name = serverName,
  49. Address = ip,
  50. Port = port,
  51. Tags = new string[] { },
  52. Check = new AgentServiceCheck()
  53. {
  54. Interval = TimeSpan.FromSeconds(12),
  55. HTTP = $"http://{ip}:{port}/Home/Health",
  56. Timeout = TimeSpan.FromSeconds(5),
  57. DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)
  58. }
  59. };
  60. client.Agent.ServiceRegister(registration);
  61. // 应用程序终止时,服务取消注册
  62. lifetime.ApplicationStopping.Register(() =>
  63. {
  64. client.Agent.ServiceDeregister(registration.ID).Wait();
  65. });
  66. }
  67. }

HomeController (主要增加了 健康检查 Health和Consul服务的获取)

  1. public class HomeController : Controller
  2. {
  3. private readonly ILogger<HomeController> _logger;
  4. public HomeController(ILogger<HomeController> logger)
  5. {
  6. _logger = logger;
  7. }
  8. public IActionResult Index()
  9. {
  10. ConsulClient client = new ConsulClient(c =>
  11. {
  12. c.Address = new Uri("http://192.168.2.7:8500/");
  13. c.Datacenter = "dc1";
  14. });
  15. return Json(client.Agent.Services().Result.Response);
  16. }
  17. public IActionResult Health()
  18. {
  19. return Ok();
  20. }
  21. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  22. public IActionResult Error()
  23. {
  24. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  25. }
  26. }

以及项目启动的命令信息如下:

  1. dotnet Server.dll --urls http://192.168.1.6:1000 --ip 192.168.1.6 --port 1000 --name server1
  2. 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 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/876356
推荐阅读
相关标签
  

闽ICP备14008679号