.net Core微服务架构之集群,服务注册和发现,客户端--多服务实例--Consul完成服务的注册与发现,框架结构图如下
Nuget下载Consul,服务注册核心代码(写了一个扩展方法)
public static class ConsuHelper
{
public static void ConsuRegist(this IConfiguration configuration)
{
try
{
//与Consul建立连接
ConsulClient client = new ConsulClient(c =>
{
c.Address = new Uri("http://localhost:8500");
c.Datacenter = "dc1";
});
string ip = configuration["ip"];//这个一定要命令行启动,不然获取不到会报错
int port = int.Parse(configuration["port"]);
//注册服务到Consul
client.Agent.ServiceRegister(new AgentServiceRegistration()
{
ID = "Service" + Guid.NewGuid(),//维一ID
Name = "lqwvje",//组名
Address = ip,//"127.0.0.1",
Port = port
});
}
catch
{
}
}
}
//下面是Startup类 Configure应用此扩展方法 这里我用的是.net core 3.0
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//TODO...
this.Configuration.ConsuRegist();
}
下面是客户端发现服务端核心代码如下
public IActionResult Test()
{
//与Consul建立连接
ConsulClient client = new ConsulClient(c =>
{
c.Address = new Uri("http://localhost:8500");
c.Datacenter = "dc1";
});
var dic = client.Agent.Services().Result.Response;//获取集群所有服务端信息
StringBuilder builder = new StringBuilder();
foreach (var agent in dic)
{
AgentService service = agent.Value;
builder.AppendLine($"ID:【{service.ID}】 组名:【{service.Service}】 IP:【{service.Address}】 端口:【{service.Port}】<br/>");
}
string result = builder.ToString();
return Content(result);
}
转载请保留原创地址http://www.luofenming.com/show.aspx?id=ART2019121800001