ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

.NET 5.0实现Consul服务注册

2021-10-28 10:33:20  阅读:185  来源: 互联网

标签:5.0 服务 serviceConfig app public consul new NET Consul


一.安装Consul

进入/usr/local/src目录

cd /usr/local/src

 下载consul安装压缩包

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

解压压缩包到当前目录

unzip consul_1.10.1_linux_amd64.zip 

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

 查看版本号

./consul --version

 版本号为v1.10.1

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

mkdir consul.server

mv consul consul.server

 

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

cd consul.server

mkdir consul.d

 

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

cd consul.d/

touch webservice.json

 

./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

 访问8500端口即可看到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();
            });
        }

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

 

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

服务健康检查成功:

 

 服务健康检查失败:

 

标签:5.0,服务,serviceConfig,app,public,consul,new,NET,Consul
来源: https://www.cnblogs.com/pudefu/p/15034011.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有