.net Core 服务 Consul的注册和调用

1. Consul的安装

到consul官网安装window版本

CMD到安装目录,执行命令:consul

Consul启动:consul agent -dev

Linux版本的按此教程:https://www.cnblogs.com/duanxz/p/10564502.html

 

2. 生产者

新建.net Core项目,程序包加入Consul依赖

新建Extensions

public static class AppBuilderExtensions
	{
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, ServiceEntity serviceEntity)
        {
            var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{serviceEntity.ConsulIP}:{serviceEntity.ConsulPort}"));//请求注册的 Consul 地址
            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔
                HTTP = $"http://{serviceEntity.IP}:{serviceEntity.Port}/api/Health",//健康检查地址
                Timeout = TimeSpan.FromSeconds(5)
            };

            // Register service with consul
            var registration = new AgentServiceRegistration()
            {
                Checks = new[] { httpCheck },
                ID = Guid.NewGuid().ToString(),
                Name = serviceEntity.ServiceName,
                Address = serviceEntity.IP,
                Port = serviceEntity.Port,
                Tags = new[] { serviceEntity.ServiceName }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别
            };

            consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)
            lifetime.ApplicationStopping.Register(() =>
            {
                consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
            });

            return app;
        }
    }

ServiceEntity:

public class ServiceEntity
	{
		public string IP { get; set; }
		public int Port { get; set; }
		public string ServiceName { get; set; }
		public string ConsulIP { get; set; }
		public int ConsulPort { get; set; }
	}

Appsetting.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "Service": {
    "Name": "server-netcore",
    "Port": "5001"
  },
  "Consul": {
    "IP": "192.168.3.154",
    "Port": "8500"
  }
}

Startup.cs

public class Startup
	{
		public Startup(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		public IConfiguration Configuration { get; }

		// This method gets called by the runtime. Use this method to add services to the container.
		public void ConfigureServices(IServiceCollection services)
		{
			services.AddControllers();
		}

		// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
		public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Microsoft.Extensions.Hosting.IApplicationLifetime lifetime)
		{
			if (env.IsDevelopment())
			{
				app.UseDeveloperExceptionPage();
			}

			app.UseRouting();

			app.UseAuthorization();

			app.UseEndpoints(endpoints =>
			{
				endpoints.MapControllers();
			});

			ServiceEntity serviceEntity = new ServiceEntity
			{
				IP = NetworkHelper.LocalIPAddress(),
				Port = Convert.ToInt32(Configuration["Service:Port"]),
				ServiceName = Configuration["Service:Name"],
				ConsulIP = Configuration["Consul:IP"],
				ConsulPort = Convert.ToInt32(Configuration["Consul:Port"])
			};
			app.RegisterConsul(lifetime, serviceEntity);
		}
	}

 

设置心跳Controller,用来Consul的健康检查

namespace Server1.Controllers
{
	[Produces("application/json")]
	[Route("api/Health")]
	public class HealthController : Controller
	{
		public IActionResult Get()
		{
			return Ok("ok");
		}
	}
}

 

写一个简单的Controller作为服务注册

namespace Server1.Controllers
{
	[Produces("application/json")]
	[Route("api/Values")]
	[ApiController]
	public class ValuesController : ControllerBase
	{
		[HttpGet]
		public string GetId()
		{
			return "Hellow Consul-netcore";
		}
	}
}

 

启动项目,查看http://localhost:8500/ui/dc1/services

 

此时服务注册成功

 

3. 消费者

新建.net Core项目,添加Consul依赖

像调用Http服务一样使用


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值