前言:常用的服务发现有
zookeeper:https://zookeeper.apache.org/
etcd:https://coreos.com/etcd/
consul:https://www.consul.io/
consul:
集成了 服务发现、故障检测、多数据中心、K/V存储。
consul安装:
只需要下载对应的可执行文件
https://www.consul.io/downloads.htmlConsul Agent有两种运行模式:
Server和Client。客户端不存储配置数据,官方建议每个Consul Cluster至少有3个或5个运行在Server模式的Agent,Client节点不限,如下图
CentOS 6.7 172.17.5.1
CentOS 7.2 172.17.5.2
Ubuntu 16.04 172.17.5.3
步骤一:
将解压后的consul执行文件放入/usr/local/bin/
步骤二:
在这三台机分别启动一个HTTP Server,我这里用的python bottle,b.py源码如下
from bottle import run, get
@get('/hello')
def hello():
return "Hello World!"
run(host='0.0.0.0', port=8080, debug=True)
步骤三:
创建配置文件存放目录
mkdir /etc/consul.d
步骤四:
在/etc/consul.d中创建文件web.json,内容如下
{
"service": {
"name": "bottle",
"tags": ["primary"],
"address": "",
"port": 8080,
"enableTagOverride": false,
"checks": [
{
"script": "/usr/local/web_check.sh",
"interval": "30s"
}
]
}
}
内容包含了服务名,IP地址,端口,检测脚本。步骤五:
在/usr/local/(路径可自定义)中创建web_check.sh,内容如下
curl -i "127.0.0.1:8080/hello" >> /dev/null 2>&1
当这个脚本返回非0状态时,consul会判断8080服务故障步骤六:
以server模式启动三台consul agent,命令如下
consul agent -server \
-data-dir=/tmp/consul -node=agent-1 -bind=172.17.5.1 \
-config-dir=/etc/consul.d
consul agent -server \
-data-dir=/tmp/consul -node=agent-2 -bind=172.17.5.2 \
-config-dir=/etc/consul.d
consul agent -server \
-data-dir=/tmp/consul -node=agent-3 -bind=172.17.5.3 \
-config-dir=/etc/consul.d
步骤七:
组成集群
在agent-2的机器执行
$ consul join 172.17.5.1
在agent-3的机器执行
$ consul join 172.17.5.1
此时再执行命令consul members,能看到集群的状态
[root@localhost daiyu]# consul members
Node Address Status Type Build Protocol DC
agent-1 172.17.5.1:8301 alive server 0.7.1 2 dc1
agent-2 172.17.5.2:8301 alive server 0.7.1 2 dc1
agent-3 172.17.5.3:8301 alive server 0.7.1 2 dc1
步骤八:
获取我们的HTTP Server可用节点,在任意一台机器上执行即可
curl 'http://localhost:8500/v1/health/service/bottle?passing'
这里可以拿回来3个成功的节点故障转移模拟:
杀掉其实一台机器的8080服务,consul会检查到服务是失败状态,再次执行获取命令
curl 'http://localhost:8500/v1/health/service/bottle?passing'
这里只可以拿回来2个成功的节点小结:
详细内容和原理讲解,建议查阅官网。
原文出自:http://blog.csdn.net/daiyudong2020/article/details/53542399
下篇文章:consul-template入门篇
End;