C#/.NET 微服务专题(consul注册服务发现的使用)

首先nuget:consul包

封装consul注册代码如下

/// <summary>
/// 自己封装的注册类
/// </summary>
public static class ConsulHelper
{
    public static void ConsulRegist(this IConfiguration configuration)
    {
        ConsulClient client = new ConsulClient(c =>
        {
            c.Address = new Uri("http://localhost:8500/");
            c.Datacenter = "dc1";
        });
        string ip = configuration["ip"];
        int port = int.Parse(configuration["port"]);//命令行参数必须传入
        //int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 1 : int.Parse(configuration["weight"]);//命令行参数必须传入
        client.Agent.ServiceRegister(new AgentServiceRegistration()
        {
            ID = "service" + Guid.NewGuid(),//唯一的
            Name = "XTGroup",//组名称-Group
            Address = ip,//其实应该写ip地址
            Port = port,//不同实例
            //Tags = new string[] { weight.ToString() },//标签
            Check = new AgentServiceCheck()//配置心跳检查的
            {
                Interval = TimeSpan.FromSeconds(12),
                HTTP = $"http://{ip}:{port}/Api/Health/Index",
                Timeout = TimeSpan.FromSeconds(5),
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5)
            }
        });
        Console.WriteLine($"http://{ip}:{port}完成注册");
    }
}

在Startup配置文件中加如下配置

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    //配置consul服务
    this.Configuration.ConsulRegist();
}

发现服务

#region 通过consul去发现这些服务地址
{
    using (ConsulClient client = new ConsulClient(c =>
    {
        c.Address = new Uri("http://localhost:8500/");
        c.Datacenter = "dc1";
    }))
    {
        var dictionary = client.Agent.Services().Result.Response;
        string message = "";
        foreach (var keyValuePair in dictionary)
        {
            AgentService agentService = keyValuePair.Value;
            this._logger.LogWarning($"{agentService.Address}:{agentService.Port} {agentService.ID} {agentService.Service}");//找的是全部服务 全部实例  其实可以通过ServiceName筛选
            message += $"{agentService.Address}:{agentService.Port};";
        }
        //获取当前consul的全部服务
        base.ViewBag.Message = message;
    }
}
#endregion
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页