基础架构 | Consul服务注册与发现

Consul服务注册与发现

Consul特性

  • 服务注册
  • 服务发现
  • 故障检测
  • K/V存储
  • 多数据中心:支持多数据中心
  • Raft算法:Consul使用Raft算法实现集群数据一致性

架构

  1. 通过API或者管理后台向consul注册服务
  2. nginx机器上部署并启动consul-template agent,其通过长轮询监听服务变更
  3. consul-template监听到变更后,动态修改upstream列表
  4. 重启nginx

Consul-Server

# 启动服务
./consul agent -server \
-bootstrap-expect 1 \
-data-dir /tmp/consul \
-bind 0.0.0.0 \
-client 0.0.0.0

# 注册服务
curl -X PUT http://127.0.0.1:8500/v1/catalog/register \
-d '{
    "Datacenter": "dc1",
    "Node": "tomcat",
    "Address": "192.168.0.1",
    "Service": {
        "Id": "192.168.1.1:8080",
        "Service": "item_jd_tomcat",
        "tags": ["dev"],
        "Port": 8080
    }
}'

curl -X PUT http://127.0.0.1:8500/v1/catalog/register \
-d '{
    "Datacenter": "dc1",
    "Node": "tomcat",
    "Address": "192.168.0.2",
    "Service": {
        "Id": "192.168.1.1:8090",
        "Service": "item_jd_tomcat",
        "tags": ["dev"],
        "Port": 8090
    }
}'

# 摘除服务
curl -X PUT http://127.0.0.1:8500/v1/catalog/dregister \
-d '{
    "Datacenter": "dc1",
    "Node": "tomcat",
    "ServiceID": "192.168.1.1:8090"
}'

# 发现服务
curl -X GET http://127.0.0.1:8500/v1/catalog/service/item_jd_tomcat

Consul-template

# vim item.jd.tomcat.ctmpl
upstream item_jd_tomcat {
    server 127.0.0.1:1111;
    {{range service "dev.item_jd_tomcat@dc1"}}
        server {{.Address}}:{{.Port}} weight=1;
    {{end}}
}

# 启动consul-template
./consul-template -consul 127.0.0.1:8500 \
-template ./item.jd.tomcat.ctmpl\
:/usr/servers/nginx/conf/domains/item.jd.tomcat\
:"./restart.sh"

restart.sh

#!/bin/bash
ps -ef | grep nginx | grep -v grep
if [ $? -ne 0 ] then
    sudo /usr/servers/nginx/sbin/nginx
    echo "nginx start"
else
    sudo /usr/servers/nginx/sbin/nginx -s reload
    echo "nginx reload"
fi

你可能感兴趣的:(基础架构 | Consul服务注册与发现)