zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Consul 基础7

2023-03-20 15:36:03 时间

注册服务

定义服务

定义服务可以使用两种方法:

  • 使用配置文件进行服务定义
  • 调用 HTTP API 进行定义

Consul 会加载配置目录中的所有配置文件,配置文件是以 .json 结尾的,并且以字典顺序加载

创建配置文件

[root@h104 consul]# mkdir /etc/consul.d
[root@h104 consul]# echo '{"service": {"name": "web", "tags": ["rails"], "port": 80}}' > /etc/consul.d/web.json
[root@h104 consul]# cat /etc/consul.d/web.json 
{"service": {"name": "web", "tags": ["rails"], "port": 80}}
[root@h104 consul]#

指定配置文件启动服务

[root@h104 consul]# consul agent -dev -bind=192.168.100.104 -config-dir /etc/consul.d/
==> Starting Consul agent...
==> Starting Consul agent RPC...
==> Consul agent running!
         Node name: 'h104'
        Datacenter: 'dc1'
            Server: true (bootstrap: false)
       Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600, RPC: 8400)
      Cluster Addr: 192.168.100.104 (LAN: 8301, WAN: 8302)
    Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false
             Atlas: <disabled>

==> Log data will now stream in as it occurs:

    2016/03/18 17:07:20 [INFO] serf: EventMemberJoin: h104 192.168.100.104
    2016/03/18 17:07:20 [INFO] serf: EventMemberJoin: h104.dc1 192.168.100.104
    2016/03/18 17:07:20 [INFO] raft: Node at 192.168.100.104:8300 [Follower] entering Follower state
    2016/03/18 17:07:20 [INFO] consul: adding LAN server h104 (Addr: 192.168.100.104:8300) (DC: dc1)
    2016/03/18 17:07:20 [INFO] consul: adding WAN server h104.dc1 (Addr: 192.168.100.104:8300) (DC: dc1)
    2016/03/18 17:07:20 [ERR] agent: failed to sync remote state: No cluster leader
    2016/03/18 17:07:22 [WARN] raft: Heartbeat timeout reached, starting election
    2016/03/18 17:07:22 [INFO] raft: Node at 192.168.100.104:8300 [Candidate] entering Candidate state
    2016/03/18 17:07:22 [DEBUG] raft: Votes needed: 1
    2016/03/18 17:07:22 [DEBUG] raft: Vote granted from 192.168.100.104:8300. Tally: 1
    2016/03/18 17:07:22 [INFO] raft: Election won. Tally: 1
    2016/03/18 17:07:22 [INFO] raft: Node at 192.168.100.104:8300 [Leader] entering Leader state
    2016/03/18 17:07:22 [INFO] raft: Disabling EnableSingleNode (bootstrap)
    2016/03/18 17:07:22 [DEBUG] raft: Node 192.168.100.104:8300 updated peer set (2): [192.168.100.104:8300]
    2016/03/18 17:07:22 [INFO] consul: cluster leadership acquired
    2016/03/18 17:07:22 [DEBUG] consul: reset tombstone GC to index 2
    2016/03/18 17:07:22 [INFO] consul: member 'h104' joined, marking health alive
    2016/03/18 17:07:22 [INFO] consul: New leader elected: h104
    2016/03/18 17:07:25 [INFO] agent: Synced service 'consul'
    2016/03/18 17:07:25 [INFO] agent: Synced service 'web'
    2016/03/18 17:08:44 [DEBUG] dns: request for {h104.node.consul. 1 1} (396.33µs) from client 127.0.0.1:48961 (udp)
    2016/03/18 17:09:15 [DEBUG] agent: Service 'consul' in sync
    2016/03/18 17:09:15 [DEBUG] agent: Service 'web' in sync
...
...
...

输出中表示 Synced service ‘web’,说明定义的服务已经成功被注册进来了,如果要以配置文件的形式注册更多的服务,可以在配置目录中添加其它的服务定义