心跳检测的使用手册

服务注册

配置文档: net 6 使用 consul 做服务注册与服务发现(上)_net 6.0 使用 consul-CSDN博客

  • 下载对应版本的consul服务
  • 三种配置方式
  1. 通过解压的文件夹进行cmd,然后在运行。
  2. 将consul文件夹的路径,添加到路径中。
  3. 注册成服务,开机自启动。
  • 需要开启consul的服务,也可以进行持久化如:Redis
  • 外网连接本地
  • 本地连接
consul.exe agent -dev -client + ip地址 //外网链接
  • 1.
consul agent -dev//开启服务
  • 1.
  • 需要下consul的.net包
  • 然后需要建立一个Consul的帮助类(弄成扩展方法)
public static class ConsulHelp
{
    public static IApplicationBuilder UseConul(this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime)
    {
        var client = new ConsulClient(options =>
        {
            options.Address = new Uri(configuration["Consul:Address"]); // Consul客户端地址
        });

        var registration = new AgentServiceRegistration
        {
            ID = Guid.NewGuid().ToString(), // 唯一Id(也就是区别服务的名称)
            Name = configuration["Consul:Name"], // 集群服务名
            Address = configuration["Consul:Ip"], // 服务绑定IP
            Port = Convert.ToInt32(configuration["Consul:Port"]), // 服务绑定端口
            Check = new AgentServiceCheck
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), // 服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10), // 健康检查时间间隔
                HTTP = $"http://{configuration["Consul:Ip"]}:{configuration["Consul:Port"]}{configuration["Consul:HealthCheck"]}", // 健康检查地址(通过配置文件拼接)判断是否健康的方法
                Timeout = TimeSpan.FromSeconds(5) // 超时时间
            }
        };

        // 注册服务
        client.Agent.ServiceRegister(registration).Wait();

        // 应用程序终止时,取消服务注册
        lifetime.ApplicationStopping.Register(() =>
        {
            client.Agent.ServiceDeregister(registration.ID).Wait();
        });

        return app;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 需要搁配置文件中添加一段配置
"Consul": {
   "Address": "http://localhost:8500/",//心跳检测的网址
   "HealthCheck": "/api/app/sheep-file/presence-state",//判断健康的方法(只要该方法可以请求就代表健康)
   "Name": "SheepFileService",//集群名称
   "Ip": "localhost",//ip如果使用Docker需要更改
   "Port": "44328"//端口号
 },
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 最后需要搁Program中进行注册
//主动去注入接口(ABP框架)
var lifetime = context.ServiceProvider.GetRequiredService<IHostApplicationLifetime>();
 var Configuration = context.ServiceProvider.GetRequiredService<IConfiguration>();
//使用扩展方法(ABP框架)
app.UseConul(Configuration, lifetime);
//其他框架
app.UseConul(builder.Configuration,app.Lifetime);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

服务注册实现的效果

会通过测试对应路径的接口方法,来判断接口是否健康。

Consul(服务注册和发现)_服务列表

服务发现

参考文章: net 6 使用 consul 做服务注册与服务发现(下)_net6 consulclient-CSDN博客

定义一个获取服务的方法,这个方法可以获取对应的集群下面的健康的服务

/// <summary>
/// 获取健康服务列表
/// </summary>
/// <returns>返回服务列表</returns>
[HttpGet]
public async Task<ResultDTO<List<string>>> GetPassingServerAsync()
{

	var consulClient = new ConsulClient(c =>
	{
		//consul地址
		c.Address = new Uri(_configuration["Consol:ConsulAddress"]);
	});
	//var services1 = consulClient.Agent.Services().Result.Response;//获取全部服务
	//获取健康的服务
	//获取当前集群下的服务
	var services = consulClient.Health.Service(_configuration["Consol:ConsulName"],null, true, null).Result.Response;
    //地址列表组装
    string[] serviceUrls = services.Select(p => $"http://{p.Service.Address + ":" + p.Service.Port}").ToArray();

	if (!serviceUrls.Any())
	{
		return new ResultDTO<List<string>> { Code = CodeType.Error, Message = "没有可用的服务" };
	}
	 return new ResultDTO<List<string>> { Code = CodeType.Success, Message = "获取服务成功!",Data= serviceUrls.ToList() };
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

实现的结果

Consul(服务注册和发现)_Consul_02

可以通过获取的所有服务结合kong进行一个负载均衡,也可以直接通过Consul一个测试

public async Task<string> GetOrder()
        {
 
            var consulClient = new ConsulClient(c =>
            {
                //consul地址
                c.Address = new Uri(_configuration["ConsulSetting:ConsulAddress"]); 
            });
            //获取健康的服务
            var services = consulClient.Health.Service("OrderService", null, true, null).Result.Response;
            //地址列表组装
            string[] serviceUrls = services.Select(p => $"http://{p.Service.Address + ":" + p.Service.Port}").ToArray();
 
            if (!serviceUrls.Any())
            {
                return await Task.FromResult("【订单服务】服务列表为空");
            }
 
            //每次随机访问一个服务实例
            var Client = new RestClient(serviceUrls[new Random().Next(0, serviceUrls.Length)]);
 
            var request = new RestRequest("/orders", Method.Get);
 
            var response = await Client.ExecuteAsync(request);
            return response.Content;
        }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

实现的效果

下面的端口发生了变化