在.net项目中使用Consul

1、创建.net core web程序并运行

2、在Consul中注册该服务

  Consul支持两种服务注册的方式,一种是通过Consul的服务注册HTTP API,由服务自身在启动后调用API注册自己,另外一种则是通过在配置文件中定义服务的方式进行注册。Consul文档中建议使用后面一种方式来做服务 配置和服务注册。Consul agent在启动时可以通过-config-dir来指定配置文件所在目录(引用自网络)

[root@linux5 ~]# consul agent -data-dir=/tmp/consul/ -node=consul5 -dc=dc1 -bind=192.168.56.105 -ui -config-dir=/tmp/consul/

在Consul启动时会读取-config-dir目录下所有的json文件来加载注册的服务,现在在该目录下创建一个配置文件:jw.json

{
  "service": {
    "name": "jw",
    "tags": ["jiewus"],
    "address": "192.168.56.1",
    "port": 1234,
    "checks": [
      {
        "http": "http://192.168.56.1:1234/Home/About",
        "interval": "10s"
      }
    ]
  }
}

重启Consul之后会发现jw这个服务:

    2017/05/10 13:59:37 [INFO] serf: EventMemberJoin: consul3 192.168.56.103
    2017/05/10 13:59:37 [INFO] serf: EventMemberJoin: consul2 192.168.56.102
    2017/05/10 13:59:37 [INFO] serf: EventMemberJoin: consul1 192.168.56.101
    2017/05/10 13:59:37 [INFO] serf: Re-joined to previously known node: consul1: 192.168.56.101:8301
    2017/05/10 13:59:37 [INFO] consul: adding server consul3 (Addr: tcp/192.168.56.103:8300) (DC: dc1)
    2017/05/10 13:59:37 [INFO] consul: adding server consul2 (Addr: tcp/192.168.56.102:8300) (DC: dc1)
    2017/05/10 13:59:37 [INFO] consul: adding server consul1 (Addr: tcp/192.168.56.101:8300) (DC: dc1)
    2017/05/10 13:59:38 [INFO] agent: Synced service 'jiewusWeb'
    2017/05/10 13:59:41 [INFO] agent: Synced check 'service:jiewusWeb'
==> Newer Consul version available: 0.8.2 (currently running: 0.8.1)

 3、使用Consul Api进行服务注册

private static void ServiceRegister(ConsulClient client)
{
    var client = new ConsulClient(ConfigurationOverview);
    var result = client.Agent.ServiceRegister(new AgentServiceRegistration()
    {
        Address = "http://192.168.56.1:1234/Home/About",
        ID = "jw",
        Name = "jw",
        Port = 1234,
        Tags = new[] { "jiewus" },
        Check = new AgentServiceCheck()
        {
            HTTP = "http://192.168.56.1:1234/Home/About",
            Interval = new TimeSpan(0, 0, 10),
            DeregisterCriticalServiceAfter = new TimeSpan(0, 1, 0),
        }
    }).Result;
}

private static void ConfigurationOverview(ConsulClientConfiguration obj)
{
    obj.Address = new Uri("http://192.168.56.104");
    obj.Datacenter = "dc1";
}

 

转载于:https://www.cnblogs.com/learn-dotnet/p/6835661.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值