NetCore 使用 Consul注册服务

第一步:通过NuGet,安装 Ocelot.Provider.Consul 包

 

第二步:配置Consul(appsettings.json)

"Consul": {
    "ServiceName": "bpm", //当前服务名称
    "IP": "127.0.0.1", //当前服务IP
    "Weight": "1",
    "Port": "5002" //当前服务端口
  }

第三步:Consul扩展类(ConsulBuilderExtensions.cs)
public static class ConsulExtensions
{
    public static void ConsulExtend(this IConfiguration configuration, string serviceName)
    {
        ConsulClient client = new(m =>
        {
            m.Address = new Uri("http://127.0.0.1:8500/");//对应服务器的地址:consul的端口
            m.Datacenter = "dc1";
        });

        //启动的时候在consul中注册实例服务
        //在consul中注册的ip, port
        string ServiceName = configuration.GetSection("Consul")["ServiceName"];
        string ip = configuration.GetSection("Consul")["IP"];
        int port = int.Parse(configuration.GetSection("Consul")["Port"]);
        int weight = int.Parse(configuration.GetSection("Consul")["Weight"]);
        client.Agent.ServiceRegister(new AgentServiceRegistration()
        {
            ID = $"{configuration["ServiceName"]}-{Guid.NewGuid()}",//唯一的
            Name = serviceName,//组(服务)名称(动态)
            Address = ip,
            Port = port,//不同的端口=>不同的实例
            Tags = new string[] { weight.ToString() },//标签
            Check = new AgentServiceCheck()//服务健康检查
            {
                Interval = TimeSpan.FromSeconds(12),//间隔1s一次 检查
                HTTP = $"http://{ip}:{port}/api/health/check",
                Timeout = TimeSpan.FromSeconds(5),//检测等待时间
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)//失败后多久移除
            }
        });
        Console.WriteLine($"{ip}:{port}--weight:{weight}");
    }
}

 

第四步:Consul注册服务(Program.cs)
builder.Configuration.ConsulExtend(builder.Configuration.GetSection("Consul")["ServiceName"]);

 

第五步:创建心跳控制器(HealthController.cs)

[Route("api/[controller]")]
[ApiController]
public class HealthController : ControllerBase
{
    [HttpGet("Check")]
    public ActionResult Check()
    {
        return Ok();
    }
}

环境变量的配置

 

配置consul为windows服务

以管理员身份启动命令提示符,执行

sc.exe create "Consul" binPath=" E:\Consul\consule.exe agent -dev"

 

启动服务

执行sc.exe start “Consul”

 

在“运行“输入services.msc进入系统服务,将Consul服务设置为自动启动

 

检查Consul服务是否正常使用:在浏览器中输入localhost:8500

 

Bat脚本启动服务:

@echo off
color F
consul agent -dev

 

posted @ 2024-01-15 11:34  microsoft-zhcn  阅读(33)  评论(0编辑  收藏  举报