.net6微服务注册到consul

  1. 在微服务的依赖上加上Consul包
  2. 配置appSettings.json配置文件如下
  //consul配置
  //1.服务名
  "ServiceName": "Order",
  //2.服务地址,本地
  "IP": "localhost",
  //3.这个端口号需要和 Properties文件夹下的 launchSettings.json中配置的 applicationUrl一样
  "Port": 9001,
  //4.consul 的健康检查地址(写一个/api/Health的controller)
  "ServiceHealthCheck": "http://localhost:9001/api/Health",
  //5.consul 地址
  "ConsulAddress": "http://localhost:8500",
  1. 创建一个注册Consul的注册类(这里读取的appsettings.json的配置信息)
public static class ConsulRegister
    {
        /// <summary>
        /// 扩展方法 将服务注册到consul
        /// </summary>
        /// <param name="configuration"></param>
        public static void RegisterConsul(this IConfiguration configuration)
        {
            #region 注册consul
            string ip = configuration["IP"];

            int port = int.Parse(configuration["Port"]);
             
            ConsulClient client = new ConsulClient(obj =>
            {
                //http://127.0.0.1:8500
                obj.Address = new Uri(configuration["ConsulAddress"]);
                obj.Datacenter = "dcl";
            });

            //向consul注册服务
            Task<WriteResult> result = client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = configuration["ServiceName"] + "_" + Guid.NewGuid(),//服务编号,不能重复,用guid最简单
                Name = configuration["ServiceName"],//服务名称
                Address = ip,
                Port = port,

                Tags = new string[] { },//可以用来设置权重
                Check = new AgentServiceCheck()
                {
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务停止多久后取消
                    Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者成为心跳间隔
                    HTTP = configuration["ServiceHealthCheck"],//健康检查地址

                    Timeout = TimeSpan.FromSeconds(5)//检测时最长等待时间
                }
            });
            #endregion

        }
    }
  1. 在Program.cs中配置注册信息(RegisterConsul()方法就是上面的注册类中的静态方法)
app.Configuration.RegisterConsul();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值