• .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();
            }

     

  • 相关阅读:
    MySQL 中 truncate 和 delete 的坑
    理解 Linux 中的 inodes
    Linux 下date命令的常见用法
    Linux 下du命令详解
    nc
    启动Tomcat时报错:错误: 代理抛出异常错误: java.rmi.server.ExportException: Port already in use: 1101; nested exception is: java.net.BindException: Address already in use: JVM_Bind
    ssm调用webservice接口并进行文件传输
    mybatis 中 执行INSERT操作后获取自增主键
    mysql时间差8小时
    生成验证码工具类
  • 原文地址:https://www.cnblogs.com/aaaaq/p/9153886.html
Copyright © 2020-2023  润新知