C#微服务心跳检测

微服务领事注册

首先要先下载Consul这个软件并安装

新建一个空项目 NuGet下载这两个包

搭建微服务框架

在配置文件appsettings.json中配置一下领事的属性

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Consul": {
    "ConsulClient": "http://10.31.59.10:8500",//需要连接的地址
    "ServiceName": "Ouyx321",				//自己的名称
    "ServiceAddress": "10.31.59.22",		 //本机IP
    "ServicePort": 5073,					//本机端口号
    "HealthUrl": "/api/Health/Index"		 //心跳检测的地址
  }
}

在Common文件夹中创建一个领事注册类 ConsulRegist.cs

 /// <summary>
 /// 领事注册
 /// </summary>
 public static class ConsulRegist
 {
     /// <summary>
     /// 领事扩展方法
     /// </summary>
     public static void ConsulExtend(this IConfiguration configuration)
     {
         //实例化consul 客户端 配置要访问的consul 地址
         ConsulClient client = new ConsulClient(x =>
         {
             //需要连接的地址
             x.Address = new Uri(configuration["Consul:ConsulClient"]);
             //名称
             x.Datacenter = "dcl";
         });
         //启动的时候再consul中注册实例服务
         //注册
         //配置文件地址
         var IPAddress = configuration["Consul:ServiceAddress"];
         //配置文件端口号
         var Port = 0;
         //显示准换为值
         int.TryParse(configuration["Consul:ServicePort"], out Port);
         //心跳检测的地址
         var HealthUrl = configuration["Consul:HealthUrl"];
         //注册一个新的服务到Consul AgentServiceRegistration()这个对象包含了注册服务所需的所有信息
         client.Agent.ServiceRegister(new AgentServiceRegistration()
         {
             //唯一标识
             ID=Guid.NewGuid().ToString(),
             //名称
             Name = configuration["Consul:ServiceName"],
             //本机ip
             Address = IPAddress,
             //本机端口号
             Port = Port,
             //健康检查(心跳检测)
             Check=new AgentServiceCheck()
             {
                 //间隔12秒检查一次
                 Interval=TimeSpan.FromSeconds(12),
                 //自己的Api地址 
                 HTTP=$"http://{IPAddress}:{Port}{HealthUrl}",
                 //等待检测时间6秒
                 Timeout=TimeSpan.FromSeconds(6),
                 //失败移除的时间
                 DeregisterCriticalServiceAfter=TimeSpan.FromSeconds(20),
             }
         });
     }
 }

然后在只读的WebApi中设置依赖项 点ConsulIolity类库勾上

再到program.cs类中注入一下方法

//将Consul 扩展方法执行
builder.Configuration.ConsulExtend();

这样代码就编辑完事了

还有一步

打开你的控制面板 选防火墙 然后选左侧高级设置 然后选择入站规则 点击新建规则 点击端口 然后下一页

特定端口输入8500 然后无脑点击下一页

然后随便起个名 点击完成就好了

然后找到你安装的consul.exe 不用打开 在路径上输入cmd敲回车

然后输入这段命令:consul agent -dev -client 0.0.0.0 -ui

敲回车

之后打开你的浏览器输入localhost:8500

见到下面这个页面就完事了

最后还有一件事 你想让其他人访问你的接口 得关闭防火墙

如果是你访问别人的可以不用关闭

posted @ 2024-03-11 10:23  Oyx。  阅读(222)  评论(1)    收藏  举报