赞
踩
随着大数据时代的到来,分布式是解决大数据问题的一个主要手段,随着越来越多的分布式的服务,如何在分布式的系统中对这些服务做协调变成了一个很棘手的问题。今天我们就来看看如何使用C# ,利用开源对分布式服务做协调
提示:以下是本篇文章正文内容,下面案例可供参考
安装Consul nuget包
代码如下(示例):
Install-Package Consul
注:这里采用方法扩展的方式处理,不懂方法扩展的可以看我 C#中的扩展方法备记 这篇文章
ConsulConfigurationEx代码如下(示例):
/// <summary> /// Consul扩展类 /// </summary> public static class ConsulRegisterEx { /// <summary> /// Configuration 扩展方法ip和端口走的命令窗体控制台, Consul 配置走的是appsettings.json 文件 /// </summary> /// <param name="configuration"></param> public static void ConsulRegister(this IConfiguration configuration) { ConsulClient client = new ConsulClient( (ConsulClientConfiguration c) => { c.Address = new Uri(configuration["Consul:Address"]); //Consul服务中心地址 c.Datacenter = configuration["Consul:DataCenter"]; //指定数据中心,如果未提供,则默认为代理的数据中心。 } ); String ip = configuration["ip"];//部署到不同服务器的时候不能写成127.0.0.1或者0.0.0.0,因为这是让服务消费者调用的地址 Int32 port = Int32.Parse(configuration["port"]); string checkUrl = configuration["Consul:CheckUrl"]; client.Agent.ServiceRegister(new AgentServiceRegistration() { ID = Guid.NewGuid().ToString(), //服务编号,不可重复 Name = configuration["Consul:ServiceName"], //服务名称 Port = port, //本程序的端口号 Address = ip, //本程序的IP地址 Check = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromMilliseconds(1), //服务停止后多久注销 Interval = TimeSpan.FromSeconds(5), //服务健康检查间隔 Timeout = TimeSpan.FromSeconds(5), //检查超时的时间 HTTP = $"http://{ip}:{port}{checkUrl}",//健康检查地址, //检查的地址 } }); } }
"Consul": {
"Address": "http://127.0.0.1:8500",
"CheckUrl": "/api/Health",
"DataCenter": "dc1",
"ServiceName": "Student2"
}
HealthController代码如下(示例):
public class HealthController : Controller
{
[Route("api/Health")]
public IActionResult Get()
{
return Ok("ok");
}
}
}
Startup 添加代码如下(示例):
//注入Consul配置
Configuration.ConsulRegister();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。