当前位置:   article > 正文

asp.net core 和consul_aspnetcore consul

aspnetcore consul

consul集群搭建

Consul是HashiCorp公司推出的使用go语言开发的开源工具,用于实现分布式系统的服务发现与配置,内置了服务注册与发现框架、分布一致性协议实现、健康检查、Key/Value存储、多数据中心方案,使用起来较为简单。使用docker命令创建注册中心比较麻烦,并且不好维护,这里使用docker-compose来实现。registrator保证了,如果服务已停止,则从注册中心中移除。docker-compose.yaml如下

  1. version: "3.0"
  2. services:
  3. # consul server,对外暴露的ui接口为8500,只有在2台consul服务器的情况下集群才起作用
  4. consulserver:
  5. image: progrium/consul:latest
  6. hostname: consulserver
  7. ports:
  8. - "8300"
  9. - "8400"
  10. - "8500:8500"
  11. - "53"
  12. command: -server -ui-dir /ui -data-dir /tmp/consul --bootstrap-expect=3
  13. # consul server1在consul server服务起来后,加入集群中
  14. consulserver1:
  15. image: progrium/consul:latest
  16. hostname: consulserver1
  17. depends_on:
  18. - "consulserver"
  19. ports:
  20. - "8300"
  21. - "8400"
  22. - "8500"
  23. - "53"
  24. command: -server -data-dir /tmp/consul -join consulserver
  25. # consul server2在consul server服务起来后,加入集群中
  26. consulserver2:
  27. image: progrium/consul:latest
  28. hostname: consulserver2
  29. depends_on:
  30. - "consulserver"
  31. ports:
  32. - "8300"
  33. - "8400"
  34. - "8500"
  35. - "53"
  36. command: -server -data-dir /tmp/consul -join consulserver
  37. registrator:
  38. image: gliderlabs/registrator:master
  39. hostname: registrator
  40. depends_on:
  41. - "consulserver"
  42. volumes:
  43. - "/var/run/docker.sock:/tmp/docker.sock"
  44. command: -internal consul://consulserver:8500

然后运行docker-compose up -d 

ASP.NET

注册服务

创建一个ServiceA(asp.net core 2.2) 项目,需要安装Consul,Consul包中提供了一个IConsulClient类,我们可以通过它来调用Consul进行服务的注册,以及发现等。我们需要在服务启动的时候,将自身的地址等信息注册到Consul中,并在服务关闭的时候从Consul撤销。这种行为就非常适合使用 IHostedService 来实现。这里要注意的是,我们需要保证_serviceId对于同一个实例的唯一,避免重复性的注册。关闭时撤销服务:ConsulHostedService.cs

  1. namespace ServiceA
  2. {
  3. using Consul;
  4. using Microsoft.AspNetCore.Hosting.Server;
  5. using Microsoft.AspNetCore.Hosting.Server.Features;
  6. using Microsoft.Extensions.Hosting;
  7. using Microsoft.Extensions.Logging;
  8. using System;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. public class ConsulHostedService : IHostedService
  14. {
  15. private readonly IConsulClient _consulClient;
  16. private readonly ILogger _logger;
  17. private readonly IServer _server;
  18. public ConsulHostedService(IConsulClient consulClient, ILogger<ConsulHostedService> logger, IServer server)
  19. {
  20. _c
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/791593
推荐阅读
相关标签
  

闽ICP备14008679号