.NET 5.0实现Consul服务注册

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了.NET 5.0实现Consul服务注册脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

一.安装Consul

进入/usr/local/src目录

cd /usr/local/src

.NET 5.0实现Consul服务注册

 下载consul安装压缩包

wget http://releases.hashicorp.COM/consul/1.10.1/consul_1.10.1_linux_amd64.zip

.NET 5.0实现Consul服务注册

解压压缩包到当前目录

unzip consul_1.10.1_linux_amd64.zip 

.NET 5.0实现Consul服务注册

 解压后有一个名字为consul的可执行文件

.NET 5.0实现Consul服务注册

 查看版本号

./consul --version

.NET 5.0实现Consul服务注册

 版本号为v1.10.1

创建consul.server目录,并把consul文件移动到coonsul.server目录

mkdir consul.server

mv consul consul.server

 

.NET 5.0实现Consul服务注册

在consul.server目录里创建consul.d目录

cd consul.server

mkdir consul.d

.NET 5.0实现Consul服务注册

 

在consul.d目录中创建webservice.json文件

cd consul.d/

touch webservice.json

.NET 5.0实现Consul服务注册

 

./consul agent -server -ui -bootstrap-expect=1 -data-dir=/usr/local/src/consul.server -node=agent-one -advertise=172.19.43.49 -bind=0.0.0.0 -client=0.0.0.0

.NET 5.0实现Consul服务注册

 访问8500端口即可看到consul注册节点

.NET 5.0实现Consul服务注册

 二.注册服务

创建一个.NET Core工程,添加Consul包。

添加一个名为HealthController的控制器,并实现一个get请求的接口用于服务健康检查,接口返回statusCode为200。

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Pudefu.Web.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HealthController : ControllerBase
    {
        [HttpGet]       
        public JsonResult Get()
        {
            return new JsonResult("OK");
        }
    }
}

 

 

在配置文件appsettings.json添加配置

  "Consulconfig": {
    "Serviceid": "d72e7de8b01a43acac640b1a00b26c81",
    "ServiceName": "pudefu.web",
    "ServiceIP": "xxx.xx.xxx.xx",//当前应用部署的服务器IP地址
    "ServicePort": 8000,//当前应用部署的服务器端口
    "ConsulIP": "xxx.xx.xxx.xx",//Consul部署的服务器IP地址
    "ConsulPort": 8500//Consul端口
  }

添加服务配置模型

public class ServiceConfig
    {
        /// <summary>
        /// 服务唯一ID
        /// </summary>
        public string ServiceId { get; set; }
        /// <summary>
        /// 服务部署的IP
        /// </summary>
        public string ServiceIP { get; set; }
        /// <summary>
        /// 服务部署的端口
        /// </summary>
        public int ServicePort { get; set; }
        /// <summary>
        /// 服务名称
        /// </summary>
        public string ServiceName { get; set; }
        /// <summary>
        /// consul部署的IP
        /// </summary>
        public string ConsulIP { get; set; }
        /// <summary>
        /// consul端口
        /// </summary>
        public int ConsulPort { get; set; }
    }

添加Consul注册类

public static class AppBuilderextensions
    {
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IHostApplicationLifetime lifetime, ServiceConfig serviceConfig)
        {
            VAR consulClient = new ConsulClient(x => x.Address = new Uri($"http://{serviceConfig.ConsulIP}:{serviceConfig.ConsulPort}"));
            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCrITicalServiceAfter = TimeSpan.FromSeconds(5),//服务器启动5秒后注册
                Interval = TimeSpan.FromMinutes(1),//每分钟检测一次(健康检查间隔时间)
                HTTP = $"http://{serviceConfig.ServiceIP}:{serviceConfig.ServicePort}/api/health",//本服务健康检查地址
                Timeout = TimeSpan.FromSeconds(20),
            };
            var registerAgent = new AgentServiceRegistration()
            {
                Check = httpCheck,
                Checks = new[] { httpCheck },
                ID = serviceConfig.ServiceId,//一定要指定服务ID,否则每次都会创建一个新的服务节点
                Name = serviceConfig.ServiceName,
                Address = serviceConfig.ServiceIP,
                Port = serviceConfig.ServicePort,
                Tags = new[] { $"urlPRefix-/{serviceConfig.ServiceName}" }//添加 urlprefix-/servicename 格式的tag标签,以便Fabio识别
            };
            consulClient.Agent.ServiceRegister(registerAgent).Wait();//服务启动时注册,使用Consul API进行注册(HttpClient发起)
            lifetime.ApplicationStopPEd.Register(() =>
            {
                consulClient.Agent.ServiceDeregister(registerAgent.ID).Wait();//服务器停止时取消注册
            });
            return app;
        }
    }

 

在Startup中添加注册代码

        public void Configure(IApplicationBuilder app, IWebHostenvironment env, IHostApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //app.UseHttpsredirection();
            //DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
            //defaultFilesOptions.DefaultFileNames.Clear();
            //defaultFilesOptions.DefaultFileNames.Add("Index.htML");
            //app.UseDefaultFiles(defaultFilesOptions);

            app.UseStatiCFiles();

            app.UseRouting();

            app.UseAuthorization();

            var serviceConfig = Configuration.GetSection("ConsulConfig").Get<ServiceConfig>();
            app.RegisterConsul(lifetime, serviceConfig);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
                endpoints.MapRazorPages();
            });
        }

 发布启动后,可见以下注册成功的服务

.NET 5.0实现Consul服务注册

 

点击pudefu.web(服务名称)这个服务可以查看服务详细信息

服务健康检查成功:

.NET 5.0实现Consul服务注册

 

 服务健康检查失败:

.NET 5.0实现Consul服务注册

 

脚本宝典总结

以上是脚本宝典为你收集整理的.NET 5.0实现Consul服务注册全部内容,希望文章能够帮你解决.NET 5.0实现Consul服务注册所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。