初识consul

初识consul

Alt text

Consul是什么?

Consul是HashiCorp公司推出的开源工具,用于实现分布式系统的服务发现与配置。Consul是分布式的、高可用的、 可横向扩展的。它具备以下特性:

服务发现 Consul的客户端可提供一个服务,比如 api 或者mysql,另外一些客户端可使用Consul去发现一个指定服务的提供者。通过DNS或者HTTP接口可以很容易的找到他所依赖的服务。健康检查 Consul客户端可提供任意数量的健康检查,指定一个服务(比如:webserver是否返回了200 OK 状态码)或者使用本地节点(比如:内存使用是否大于90%). 这个信息可由operator用来监视集群的健康。服务发现组件用来避免将流量发送到不健康的主机。Key/Value存储 应用程序可根据自己的需要使用Consul的Key/Value存储.比如动态配置,功能标记,协调,领袖选举等等,简单的HTTP API让他更易于使用。多数据中心 Consul支持开箱即用的多数据中心.这意味着用户不需要担心需要建立额外的抽象层让业务扩展到多个区域。Consul面向DevOps和应用开发者友好,使他适合现代弹性的基础设施。

Consul架构

Alt text

Consul是一个分布式高可用的系统。
Agent与一个和多个Consul Server 进行交互.Consul Server 用于存放和复制数据.server自行选举一个leader。虽然Consul可以运行在一台server , 但是建议使用3到5台来避免失败情况下数据的丢失。每个数据中心建议配置一个server集群。

Consul部署

Consul用Golang实现,因此具有天然可移植性(支持 Linux、windows 和macOS)。安装包仅包含一个可执行文件(这是由golang语言特性决定的)。Consul安装非常简单,只需要下载对应系统的软件包并解压后就可使用。

常见以Linux平台为例:

123
$ wget https://releases.hashicorp.com/consul/0.8.5/consul_0.8.5_linux_amd64.zip$ unzip consul_0.8.5_linux_amd64.zip$ mv consul /usr/local/bin/

安装完即可执行命令验证:

123456789101112131415161718192021222324
$ consulusage: consul [--version] [--help] <command> [<args>]Available commands are:   agent          Runs a Consul agent   event          Fire a new event   exec           Executes a command on Consul nodes   force-leave    Forces a member of the cluster to enter the "left" state   info           Provides debugging information for operators.   join           Tell Consul agent to join cluster   keygen         Generates a new encryption key   keyring        Manages gossip layer encryption keys   kv             Interact with the key-value store   leave          Gracefully leaves the Consul cluster and shuts down   lock           Execute a command holding a lock   maint          Controls node or service maintenance mode   members        Lists the members of a Consul cluster   monitor        Stream logs from a Consul agent   operator       Provides cluster-level tools for Consul operators   reload         Triggers the agent to reload configuration files   rtt            Estimates network round trip time between nodes   snapshot       Saves, restores and inspects snapshots of Consul server state   validate       Validate config files/directories   version        Prints the Consul version   watch          Watch for changes in Consul

开发模式

consul 开发者模式,可以快速开启单节点的 consul服务,具有完整功能,方便开发测试。

1
consul agent -dev

consul members 命令查看当前集群的节点情况

123
dev@ubuntu ~$ consul membersNode    Address         Status  Type    Build  Protocol  DCubuntu  127.0.0.1:8301  alive   server  0.7.2  2         dc1

HTTP API

members命令选项的输出是基于gossip协议的并且其内容是最终一致。也就是说,在任何时候你在本地代理看到的内容可能与当前服务器中的状态并不是绝对一致的。

如果需要强一致性的状态信息,使用HTTP API向Consul服务器发送请求:

12345678910111213
dev@ubuntu ~$ curl localhost:8500/v1/catalog/nodes[    {        "Node": "ubuntu",        "Address": "127.0.0.1",        "TaggedAddresses": {            "lan": "127.0.0.1",            "wan": "127.0.0.1"        },        "CreateIndex": 4,        "ModifyIndex": 5    }]

服务可以通过配置文件注册,也可以通过HTTP API 添加。这里以配置文件定义服务:

1234567
cd ~/consul// 创建etc 目录用于存放配置文件mkdir etc// 创建web.json 配置文件echo '{"service": {"name": "web", "tags": ["nginx"], "port": 80}}' | tee ~/consul/etc/web.json// 重启consul,并指定配置文件目录consul agent -dev -config-dir=/home/dev/consul/etc

WEB界面

Consul自带一个界面美观,功能强大的,开箱即用的Web界面。通过该界面我们可以查看所有的服务以及节点,查看所有的健康监测及其当前的状态,以及读取和设置键/值数据。

该界面被映射到/ui上,和HTTP API使用相同的端口。默认就是http://localhost:8500/ui
Alt text

服务注册

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

1234
# 创建配置目录$ mkdir /etc/consul.d# 创建一个服务定义配置文件,假设有一个名为web服务,它运行在80端口。$ echo '{"service": {"name": "web", "tags": ["rails"], "port": 80}}' >/etc/consul.d/web.json

用指定配置文件启动服务

123
$ consul agent -dev -bind=192.168.50.210 -config-dir /etc/consul.d/==> Starting Consul agent...==> Consul agent running!

查询服务

一旦agent启动并且服务同步了.我们可以通过DNS或者HTTP的API来查询服务.

DNS API

让我们首先使用DNS API来查询.在DNS API中,服务的DNS名字是 NAME.service.consul. 虽然是可配置的,但默认的所有DNS名字会都在consul命名空间下.这个子域告诉Consul,我们在查询服务,NAME则是服务的名称.
对于我们上面注册的Web服务.它的域名是 web.service.consul :

12345678910111213141516
$ dig @127.0.0.1 -p 8600  rails.web.service.consul; <<>> DiG 9.10.3-P4-Ubuntu <<>> @127.0.0.1 -p 8600 rails.web.service.consul; (1 server found);; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 44287;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0;; WARNING: recursion requested but not available;; QUESTION SECTION:;rails.web.service.consul.INA;; ANSWER SECTION:rails.web.service.consul. 0INA192.168.2.210;; Query time: 0 msec;; SERVER: 127.0.0.1#8600(127.0.0.1);; WHEN: Tue May 09 10:58:16 CST 2017;; MSG SIZE  rcvd: 58

HTTP API

除了DNS API之外,HTTP API也可以用来进行服务查询:

1234567891011121314151617181920212223
$ curl http://localhost:8500/v1/catalog/service/web[    {        "ID": "b76ff298-accd-05ff-8c64-5d79d866dfa9",        "Node": "dev-master-01",        "Address": "192.168.50.210",        "TaggedAddresses": {            "lan": "192.168.50.210",            "wan": "192.168.50.210"        },        "NodeMeta": {},        "ServiceID": "web",        "ServiceName": "web",        "ServiceTags": [            "rails"        ],        "ServiceAddress": "",        "ServicePort": 80,        "ServiceEnableTagOverride": false,        "CreateIndex": 7,        "ModifyIndex": 7    }]

调用HTTP API进行定义

Consul提供RESTful HTTP API. API可对节点、服务、健康检查、配置等执行CRUD操作(CRUD是指在做计算处理时的增加(Create)、读取查询(Retrieve)、更新(Update)和删除(Delete))。其语法类似solr和elasticsearch的接口语法。

Consul Endpoint主要支持以下接口:

acl – 访问控制列表agent – Agent控制catalog – 管理nodes和servicescoordinate – 网络协同event – 用户事件health – 管理健康监测kv – K/V存储query - Prepared Queriessession – 管理会话status – Consul系统状态

具体的API使用语法可参照文档:https://www.consul.io/api/index.html,我就不贴demo了。

文章来源:

Author:hyperxu
link:http://www.hyperxu.com/2017/07/01/20170701-2/