.NET Core微服务使用Consul实现服务注册/发现/健康检查

 关于Consul的更多介绍,比如优点,这里就不再赘述了,上网一搜就可以随处找到了。但是,必须贴一个和其他类似软件的对比:

关于Consul的架构以及相关的角色

 

基于IApplicationBuilder写一个扩展方法,用于调用Consul API

   public static class RegisterService
    {
        const string _consulIP = "192.168.200.145";
        const int _consulPort = 8500;
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, IHostingEnvironment env)
        {
            var server = AppConfiguration.Configurations["urls"];
            if (server.IsContains("/") && server.Contains(":"))
            {
                var str = server.Split('/').LastOrDefault().Split(':');
                string _ip = str.FirstOrDefault();
                int _port = Convert.ToInt32(str.LastOrDefault());
                try
                {
                    if (_ip.IsNotNull() && _port > 0)
                    {
                        var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{_consulIP}:{_consulPort}"));//请求注册的 Consul 地址
                        var httpCheck = new AgentServiceCheck()
                        {
                            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(1),//服务启动多久后注册
                            Interval = TimeSpan.FromSeconds(1),//健康检查时间间隔,或者称为心跳间隔
                            HTTP = $"http://{_ip}:{_port}/api/health",//健康检查地址
                            Timeout = TimeSpan.FromSeconds(5)
                        };
                        var registration = new AgentServiceRegistration()
                        {
                            Checks = new[] { httpCheck },
                            ID = Guid.NewGuid().ToString(),
                            Name = env.ApplicationName,
                            Address = _ip,
                            Port = _port,
                            Tags = new[] { $"urlprefix-/{env.ApplicationName}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别
                        };
                        consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)
                        lifetime.ApplicationStopping.Register(() =>
                        {
                            consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
                        });
                        return app;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"注册服务器{_consulIP}:{_consulPort}:", ex);
                }
            }
            throw new Exception("服务(注册/发现)获取Host失败");
        }
    }
View Code

 

在Starup类的Configure方法中,调用此扩展方法调用:

      public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();
            Configures<TokenProvider>(app, env);
            app.RegisterConsul(lifetime, env);
            app.UseMvc();
        }

 

 

转载于:https://www.cnblogs.com/aaaaq/p/9153886.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值