consual簡介
Consul是由HashiCorp開發的一個支持多數據中心的分布式服務發現和鍵值對存儲服務的開源軟件,被大量應用于基于微服務的軟件架構當中。
用戶可以通過Consul官網下載對應操作系統版本的軟件包。Consul與Prometheus同樣使用Go語言進行開發,因此安裝和部署的方式也極為簡單,解壓并將命令行工具放到系統PATH路徑下即可。
在本地可以使用開發者模式在本地快速啟動一個單節點的Consul環境:
$ consul agent -dev
==> Starting Consul agent...
==> Consul agent running!
Version: 'v1.0.7'
Node ID: 'd7b590ba-e2f8-3a82-e8a8-2a911bdf67d5'
Node name: 'localhost'
Datacenter: 'dc1' (Segment: '<all>')
Server: true (Bootstrap: false)
Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, DNS: 8600)
Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false
在啟動成功后,在一個新的terminal窗口中運行consul members可以查看當前集群中的所有節點:
$ consul members
Node Address Status Type Build Protocol DC Segment
localhost 127.0.0.1:8301 alive server 1.0.7 2 dc1 <all>
用戶還可以通過HTTP API的方式查看當前集群中的節點信息:
$ curl localhost:8500/v1/catalog/nodes
[
{
"ID": "d7b590ba-e2f8-3a82-e8a8-2a911bdf67d5",
"Node": "localhost",
"Address": "127.0.0.1",
"Datacenter": "dc1",
"TaggedAddresses": {
"lan": "127.0.0.1",
"wan": "127.0.0.1"
},
"Meta": {
"consul-network-segment": ""
},
"CreateIndex": 5,
"ModifyIndex": 6
}
]
Consul還提供了內置的DNS服務,可以通過Consul的DNS服務的方式訪問其中的節點:
$ dig @127.0.0.1 -p 8600 localhost.node.consul
; <<>> DiG 9.9.7-P3 <<>> @127.0.0.1 -p 8600 localhost.node.consul
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 50684
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;localhost.node.consul. IN A
;; ANSWER SECTION:
localhost.node.consul. 0 IN A 127.0.0.1
;; Query time: 5 msec
;; SERVER: 127.0.0.1#8600(127.0.0.1)
;; WHEN: Sun Apr 15 22:10:56 CST 2018
;; MSG SIZE rcvd: 66
在Consul當中服務可以通過服務定義文件或者是HTTP API的方式進行注冊。這里使用服務定義文件的方式將本地運行的node_exporter通過服務的方式注冊到Consul當中。
sudo mkdir /etc/consul.d
echo '{"service": {"name": "node_exporter", "tags": ["exporter"], "port": 9100}}' \
| sudo tee /etc/consul.d/node_exporter.json
重新啟動Consul服務,并且聲明服務定義文件所在目錄:
$ consul agent -dev -config-dir=/etc/consul.d
==> Starting Consul agent...
2018/04/15 22:23:47 [DEBUG] agent: Service "node_exporter" in sync
一旦服務注冊成功之后,用戶就可以通過DNS或HTTP API的方式查詢服務信息。默認情況下,所有的服務都可以使用NAME.service.consul域名的方式進行訪問。
例如,可以使用node_exporter.service.consul域名查詢node_exporter服務的信息。
除了使用DNS的方式以外,Consul還支持用戶使用HTTP API的形式獲取服務列表:localhost:8500/v1/catalog/service/node_exporter。
與Promethues集成
Consul作為一個通用的服務發現和注冊中心,記錄并且管理了環境中所有服務的信息。Prometheus通過與Consul的交互可以獲取到相應Exporter實例的訪問信息。在Prometheus的配置文件當可以通過以下方式與Consul進行集成:
- job_name: node_exporter
metrics_path: /metrics
scheme: http
consul_sd_configs:
- server: localhost:8500
services:
- node_exporter
在consul_sd_configs定義當中通過server定義了Consul服務的訪問地址,services則定義了當前需要發現哪些類型服務實例的信息,這里限定了只獲取node_exporter的服務實例信息。