C#-使用Consul

Consul是一个服务网格解决方案,提供了一个功能齐全的控制平面,具有服务发现、配置和分段功能。

下载安装Consul,直接去官网(Consul by HashiCorp)下载即可。

启动Consul,访问consul主页,默认为http://localhost:8500。

#开发模式启动
consul agent -dev

将服务注册到Consul,首先需要下载consul的nuget包,在包管理器中,搜索consul进行安装,使用扩展方法封装一个通用的注册方法:

//ConsulRegistryExtensions.cs
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace ConsulHelper
{
    public static class ConsulRegistryExtensions
    {
        public static IApplicationBuilder UseConul(this IApplicationBuilder applicationBuilder, IConfiguration configuration, IHostApplicationLifetime lifetime) 
        {
            try
            {
                string ip = configuration["Consul:Ip"];
                int port = Convert.ToInt32(configuration["Consul:Port"]);
                string serviceName = configuration["Consul:ServiceName"];
                var serviceId = Guid.NewGuid().ToString();
                var consulHost = configuration["Consul:ConsulHost"];
                var consulDataCenter = configuration["Consul:ConsulDataCenter"];
                //创建consul的连接对象
                var consulClient = new ConsulClient(c =>
                {
                    c.Address = new Uri(consulHost);
                    c.Datacenter = consulDataCenter;
                });
                AgentServiceRegistration agentServiceRegistration = new AgentServiceRegistration()
                {
                    ID = serviceId,
                    Name = serviceName,
                    Address = ip,
                    Port = port,
                    Check = new AgentServiceCheck()
                    {
                        Interval = TimeSpan.FromSeconds(10),
                        HTTP = $"http://{ip}:{port}/Api/ApiHealth",
                        Timeout = TimeSpan.FromSeconds(10),
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)
                    }
                };
                //将服务注册到consul上
                consulClient.Agent.ServiceRegister(agentServiceRegistration).Wait();
                //注销实例
                lifetime.ApplicationStopped.Register(async () =>
                {
                    await consulClient.Agent.ServiceDeregister(serviceId);
                });
            }
            catch(Exception ex)
            {
            }
            return applicationBuilder;
        }
    }
}

配置文件中的参数配置:

  "Consul": {
    "Ip": "127.0.0.1",
    "Port": "5272",
    "ServiceName": "ContentService",
    "ConsulHost": "http://127.0.0.1:8500",
    "ConsulDataCenter": "dc1"
  }

在WebApi项目的Controller文件夹中,创建心跳检测接口:

//ApiHealthController.cs
using Microsoft.AspNetCore.Mvc;

namespace ContentService.WebApi.Controllers
{
    [Route("Api/[controller]")]
    public class ApiHealthController:Controller
    {
        [HttpGet]
        public IActionResult Get()
        {
            return Ok("ok");
        }
    }
}

在Program.cs中调用刚才我们写的扩展方法:

//服务注册到consul中
IConfiguration configuration = app.Configuration;
IHostApplicationLifetime lifetime = app.Lifetime;
app.UseConul(configuration, lifetime);

启动服务,可以看到服务已经成功添加到Consul中了。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注