consul 配合 .net core 的基本操作分布式集群+心跳检测
https://www.consul.io/downloads
在根目录 执行 cmd.exe
--启动开始
consul agent -dev
打开浏览器 这里建议 谷歌和 最新的IE浏览器
http://localhost:8500/
-------------------------------- 以下是.net core 6.0代码
在Program.cs 文件中
引入依赖项 NuGet Consul
#region 注册 consul
//Eleven.MicroService.BaseFunction.ConsulHelper.ConsulRegist(app.Configuration);
ConsulClient client = new ConsulClient(c =>
{
c.Address = new Uri("http://localhost:8500/");
c.Datacenter = "dcl";
});
string ip = app.Configuration["ip"];
int port = int.Parse(app.Configuration["port"]);//命令行参数必须传入10001;//
int weight = string.IsNullOrWhiteSpace(app.Configuration["weight"]) ? 1 :
int.Parse(app.Configuration["weight"]);
//服务注册
client.Agent.ServiceRegister(new AgentServiceRegistration()
{
ID = "service" + Guid.NewGuid(),//唯一ID
Name = "ElevenService",//分组名称-Group
Address = ip,//其实应该写ip地址
Port = port,//不同实例
Tags = new string[] { weight.ToString() },//标签
Check = new AgentServiceCheck()//心跳检测机制
{
Interval = TimeSpan.FromSeconds(12),//间隔5s一次
HTTP = $"http://{ip}:{port}/Api/Test/Index",//心跳检测地址
Timeout = TimeSpan.FromSeconds(5),//检测等待时间 5s
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(120)//失败后多久移除
}
});
Console.WriteLine($"{ip} : {port}--weight : {weight}");
#endregion
---------------------------------------------------------------------------------------然后通过 一个终端来调用 consul
新建一个 API或者控制器
#region 单个分布式
//string url = "httv://localhost:8080/api/users/all";//8080就等同于3个实例--负载均衡策略由Nginx完成l / string content - this.InvokeApi(ur1) ;
//Console.WriteLine($"This is {url} Invoke" ) ;
//tools.InvokeApi(url);
#endregion
#region Consul
ConsulClient client = new ConsulClient(a => {
a.Address = new Uri("http://localhost:8500/");
a.Datacenter = "dcl";
});
var response = client.Agent.Services().Result.Response;
string url = "http://ElevenService/api/User/GetList";
Uri uri = new Uri(url);
string groupName = uri.Host;
AgentService agentService = null;
var serviceDictionary = response.Where(a=> a.Value.Service.Equals(groupName,StringComparison.OrdinalIgnoreCase)).ToArray();
{
//均衡平均负载
agentService = serviceDictionary[orderIndex++ % serviceDictionary.Length].Value;//拿走 consul 中配置的第一个
}
{
////平均策略--随机获取索引--相对就平均
//agentService = serviceDictionary[new Random(orderIndex++).Next(0, serviceDictionary.Length)].Value;
}
url = $"{uri.Scheme}://{agentService.Address}:{agentService.Port}{uri.PathAndQuery}";
string result_json = tools.InvokeApi(url);
Console.WriteLine($"This is {url} Invoke");
#endregion
return result_json + "--------------" + url;
----------------------------------------------------------------------访问工具
public class tools
{
public static string InvokeApi(string ur1)
{
using (HttpClient httpClient = new HttpClient())
{
HttpRequestMessage message = new HttpRequestMessage();
message.Method = HttpMethod.Get;
message.RequestUri = new Uri(ur1);
var result = httpClient.SendAsync(message).Result;
string content = result.Content.ReadAsStringAsync().Result;
return content;
}
}
}
--------------------------------------------------------
总结:
1)由于consul 心跳检测机制 添加时很好用 但 关闭的时候 存在 延迟问题 建议 在 访问的控制终端中 增加try 或者判断处理 如果 如果出现异常直接 index++进行下一个 处理
2)记得使用谷歌浏览器 或者最新的IE

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通