NoSQLConsul中服务注册的两种方式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NoSQLConsul中服务注册的两种方式相关的知识,希望对你有一定的参考价值。
一句话
用agent更优雅,适合agent遍布每个应用机的情况。用catalog更直接,操作更方便
前言
今天遇到写一个服务启动自注册的逻辑时产生了一点纠结,可以使用agent
对象的register
方法进行注册,也可以使用catalog
的register
方法进行注册。那么,两种方式有什么区别呢?
agent对象
new 一个consulClient对象,应当是作为一个软consul agent
- 对API URL对应的节点的属性没有要求. 其可以是server身份也可以是纯agent身份
- 数据要经过冲突确认后,再存入catalog中
- 反注册时只可以反注册自身的节点(主机)上的服务,注册时可以注册其他主机上的服务
catalog
connect to consul database
- 连接的节点应当是server节点
- 操作后数据立马生效
- 反注册对所有节点生效
用途
- 编写反注册节点的服务应使用catalog的方法
- 使用agent方法反注册服务时,需要指定一个serviceID参数,该ID是的唯一维度是node也就是主机唯一的。因此从catalog进行反注册时最好是提供主机名和服务ID,当然也可以是IP和服务ID,服务名和服务ID的结合我没有尝试过。
案例
实现反注册节点的逻辑
用途:删除已经失效的主机信息,用于取消报警触发
// 根据IP删除节点
func (c *ConsulHelper) DropNodeByIP(ip string) error {
// STEP1: 查找IP在Consul中对应的NodeName
nodeName, err := c.FindNodeNameByIP(ip)
if err != nil {
return err
}
p.Infof("Find node %s by ip %s success, ", nodeName, ip)
// STEP2: 调用DropNode删除节点
err = c.DropNode(nodeName)
if err != nil {
p.Errorf("Drop Node by ip: %s failed, %+v", ip, err)
return err
}
return nil
}
func (c *ConsulHelper) DropNode(nodeName string) error {
var bom = consul.CatalogDeregistration{
Node: nodeName,
Datacenter: common.CONF.Consul.DataCenter,
}
_, err := c.API.Catalog().Deregister(&bom, nil)
return err
}
func (c *ConsulHelper) DropSelfNode() error {
return c.DropNode(c.hostUniqueName)
}
实现反注册服务的逻辑
用途:服务启动时向consul注册自身,服务正常关闭时将自身从consul中反注册
```c#
/// <summary>
/// 反注册服务(使用catalog实现)
/// </summary>
/// <param name="nodeIP"></param>
/// <param name="serviceID"></param>
/// <returns></returns>
public WriteResult DeregisterService(string nodeIP, string serviceID)
{
this.logger.LogDebug($"Now start DeregisterService in {nodeIP}, service:{serviceID}");
var x = new CatalogDeregistration { Datacenter = "dc1", Address = nodeIP, ServiceID= serviceID };
return this.consul.Catalog.Deregister(x).Result;
}
/// <summary>
/// 注册服务(使用Agent实现)
/// </summary>
/// <param name="serviceRegistration"></param>
public void RegisterService(AgentServiceRegistration serviceRegistration)
{
this.logger.LogDebug("Now do service register");
this.consul.Agent.ServiceRegister(serviceRegistration);
}
/// <summary>
/// 反注册本机上的服务(使用Agent实现)
/// </summary>
/// <param name="serviceID">本机唯一的服务ID</param>
public void DeregisterSelfNodeService(string serviceID)
{
this.logger.LogDebug("Now do service deregister");
this.consul.Agent.ServiceDeregister(serviceID);
}
private void OnStarted(IConsulService consulService)
{
var exposedHTTPURL = this.Configuration["Kestrel:EndPoints:Http:Url"];
var stringPort = exposedHTTPURL.Split(":")[^1];
consulService.RegisterSelfProject(int.Parse(stringPort));
}
private void OnStopped(IConsulService consulService)
{
var exposedHTTPURL = this.Configuration["Kestrel:EndPoints:Http:Url"];
var stringPort = exposedHTTPURL.Split(":")[^1];
consulService.DeregisterSelfProject(int.Parse(stringPort));
}
输出:
```bash
2020/04/23 17:59:26 [WARN] agent: Node name "PsyDuck.local" will not be discoverable via DNS due to invalid characters. Valid characters include all alpha-numerics and dashes.
2020/04/23 17:59:26 [INFO] raft: Restored from snapshot 13-163854-1558515302742
2020/04/23 17:59:26 [INFO] raft: Initial configuration (index=1): [{Suffrage:Voter ID:e15ef033-ec5c-f2c5-4679-43fdfa69f508 Address:10.100.100.1:8300}]
2020/04/23 17:59:26 [INFO] raft: Node at 127.0.0.1:8300 [Follower] entering Follower state (Leader: "")
2020/04/23 17:59:26 [INFO] serf: EventMemberJoin: PsyDuck.local.dc1 127.0.0.1
2020/04/23 17:59:26 [WARN] serf: Failed to re-join any previously known node
2020/04/23 17:59:26 [INFO] serf: EventMemberJoin: PsyDuck.local 127.0.0.1
2020/04/23 17:59:26 [WARN] serf: Failed to re-join any previously known node
2020/04/23 17:59:26 [INFO] consul: Adding LAN server PsyDuck.local (Addr: tcp/127.0.0.1:8300) (DC: dc1)
2020/04/23 17:59:26 [INFO] consul: Handled member-join event for server "PsyDuck.local.dc1" in area "wan"
2020/04/23 17:59:26 [INFO] agent: Started DNS server 0.0.0.0:8600 (tcp)
2020/04/23 17:59:26 [INFO] agent: Started DNS server 0.0.0.0:8600 (udp)
2020/04/23 17:59:26 [INFO] agent: Started HTTP server on [::]:8500 (tcp)
2020/04/23 17:59:26 [INFO] agent: started state syncer
2020/04/23 17:59:33 [ERR] agent: failed to sync remote state: No cluster leader
2020/04/23 17:59:35 [WARN] raft: Heartbeat timeout from "" reached, starting election
2020/04/23 17:59:35 [INFO] raft: Node at 127.0.0.1:8300 [Candidate] entering Candidate state in term 14
2020/04/23 17:59:35 [INFO] raft: Election won. Tally: 1
2020/04/23 17:59:35 [INFO] raft: Node at 127.0.0.1:8300 [Leader] entering Leader state
2020/04/23 17:59:35 [INFO] consul: cluster leadership acquired
2020/04/23 17:59:35 [INFO] consul: New leader elected: PsyDuck.local
2020/04/23 17:59:35 [INFO] consul: member ‘PsyDuck.local‘ joined, marking health alive
2020/04/23 17:59:36 [INFO] agent: Synced node info
==> Failed to check for updates: Get https://checkpoint-api.hashicorp.com/v1/check/consul?arch=amd64&os=darwin&signature=01a8a19a-0919-6b96-8aa1-eaf5f977a351&version=1.4.2: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
2020/04/23 18:00:05 [WARN] agent: Service name "监控系统" will not be discoverable via DNS due to invalid characters. Valid characters include all alpha-numerics and dashes.
2020/04/23 18:00:05 [INFO] agent: Synced service "监控系统@127.0.0.1:5007"
2020/04/23 18:00:29 [INFO] agent: Deregistered service "监控系统@127.0.0.1:5007"
2020/04/23 18:02:06 [INFO] agent: Synced service "DBAMonitorAPI@127.0.0.1:5007"
以上是关于NoSQLConsul中服务注册的两种方式的主要内容,如果未能解决你的问题,请参考以下文章