C#- 使用 Consul
作者:小毅
- 2022-12-29 湖北
本文字数:1675 字
阅读完需:约 5 分钟
Consul 是一个服务网格解决方案,提供了一个功能齐全的控制平面,具有服务发现、配置和分段功能。
下载安装 Consul,直接去官网(Consul by HashiCorp)下载即可。
启动 Consul,访问 consul 主页,默认为 http://localhost:8500。
#开发模式启动
consul agent -dev
复制代码
将服务注册到 Consul,首先需要下载 consul 的 nuget 包,在包管理器中,搜索 consul 进行安装,使用扩展方法封装一个通用的注册方法:
//ConsulRegistryExtensions.cs
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
namespace ConsulHelper
{
public static class ConsulRegistryExtensions
{
public static IApplicationBuilder UseConul(this IApplicationBuilder applicationBuilder, IConfiguration configuration, IHostApplicationLifetime lifetime)
{
try
{
string ip = configuration["Consul:Ip"];
int port = Convert.ToInt32(configuration["Consul:Port"]);
string serviceName = configuration["Consul:ServiceName"];
var serviceId = Guid.NewGuid().ToString();
var consulHost = configuration["Consul:ConsulHost"];
var consulDataCenter = configuration["Consul:ConsulDataCenter"];
//创建consul的连接对象
var consulClient = new ConsulClient(c =>
{
c.Address = new Uri(consulHost);
c.Datacenter = consulDataCenter;
});
AgentServiceRegistration agentServiceRegistration = new AgentServiceRegistration()
{
ID = serviceId,
Name = serviceName,
Address = ip,
Port = port,
Check = new AgentServiceCheck()
{
Interval = TimeSpan.FromSeconds(10),
HTTP = $"http://{ip}:{port}/Api/ApiHealth",
Timeout = TimeSpan.FromSeconds(10),
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)
}
};
//将服务注册到consul上
consulClient.Agent.ServiceRegister(agentServiceRegistration).Wait();
//注销实例
lifetime.ApplicationStopped.Register(async () =>
{
await consulClient.Agent.ServiceDeregister(serviceId);
});
}
catch(Exception ex)
{
}
return applicationBuilder;
}
}
}
复制代码
配置文件中的参数配置:
"Consul": {
"Ip": "127.0.0.1",
"Port": "5272",
"ServiceName": "ContentService",
"ConsulHost": "http://127.0.0.1:8500",
"ConsulDataCenter": "dc1"
}
复制代码
在 WebApi 项目的 Controller 文件夹中,创建心跳检测接口:
//ApiHealthController.cs
using Microsoft.AspNetCore.Mvc;
namespace ContentService.WebApi.Controllers
{
[Route("Api/[controller]")]
public class ApiHealthController:Controller
{
[HttpGet]
public IActionResult Get()
{
return Ok("ok");
}
}
}
复制代码
在 Program.cs 中调用刚才我们写的扩展方法:
//服务注册到consul中
IConfiguration configuration = app.Configuration;
IHostApplicationLifetime lifetime = app.Lifetime;
app.UseConul(configuration, lifetime);
复制代码
启动服务,可以看到服务已经成功添加到 Consul 中了。
划线
评论
复制
发布于: 刚刚阅读数: 3
小毅
关注
还未添加个人签名 2019-09-11 加入
还未添加个人简介
评论