consul 使用


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace UFX.SCM.OpenApi.Settings
{
    /// <summary>
    /// 服务注册配置
    /// </summary>
    public class ConsulSetting
    {
        /// <summary>
        /// 服务注册地址
        /// </summary>
        public string Address { get; set; }
        /// <summary>
        /// 数据中心
        /// </summary>
        public string Datacenter { get; set; }

    }
}

 

using Consul;
using Microsoft.Extensions.Configuration;
using System;
using UFX.SCM.OpenApi.Settings;

namespace UFX.SCM.OpenApi.Helpers
{
    /// <summary>
    /// consul帮助类
    /// </summary>
    public static class ConsulHelper
    {
        /// <summary>
        /// 服务注册
        /// </summary>
        /// <param name="configuration"></param>
        public static void ConsulRegister(this IConfiguration configuration)
        {
            var setting = configuration.GetSection("ConsulSetting").Get<ConsulSetting>();
            var urls = configuration.GetSection("urls").Get<string>();
            var url = new Uri(urls);
            ConsulClient client = new(m =>
            {
                m.Address = new Uri(setting.Address);
                m.Datacenter = setting.Datacenter;
            });
            //启动的时候在consul中注册实例服务
            //在consul中注册的ip,port
            string ip = url.Host;
            int port = url.Port;
            int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 1 : int.Parse(configuration["weight"]);
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = "OpenApi-" + Guid.NewGuid(),//唯一的
                Name = "OpenApi",//组(服务)名称
                Address = ip,
                
                Port = port,//不同的端口=>不同的实例
                Tags = new string[] { weight.ToString() },//标签
                Check = new AgentServiceCheck()//服务健康检查
                {
                    Interval = TimeSpan.FromSeconds(12),//间隔12s一次 检查
                    HTTP = $"{urls}/Health",
                    Timeout = TimeSpan.FromSeconds(5),//检测等待时间
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)//失败后多久移除
                }
            });
            Console.WriteLine($"{urls}--weight:{weight}");
        }
    }
}

 

posted @ 2023-01-13 10:39  浅草青晨  阅读(24)  评论(0编辑  收藏  举报