python使用consul进行服务注册和发现

 


一、安装启动consul

1.通过docker快速安装

#获取docker镜像
docker pull consul

2.启动consul

然后就可以启动集群了,这里启动4个Consul Agent,3个Server(会选举出一个leader),1个Client

复制代码
#启动第1个Server节点,集群要求要有3个Server,将容器8500端口映射到主机8900端口,同时开启管理界面
docker run -d --name=consul1 -p 8900:8500 -e CONSUL_BIND_INTERFACE=eth0 consul agent --server=true --bootstrap-expect=3 --client=0.0.0.0 -ui
 
#启动第2个Server节点,并加入集群
docker run -d --name=consul2 -e CONSUL_BIND_INTERFACE=eth0 consul agent --server=true --client=0.0.0.0 --join 172.17.0.2
 
#启动第3个Server节点,并加入集群
docker run -d --name=consul3 -e CONSUL_BIND_INTERFACE=eth0 consul agent --server=true --client=0.0.0.0 --join 172.17.0.2
 
#启动第4个Client节点,并加入集群
docker run -d --name=consul4 -e CONSUL_BIND_INTERFACE=eth0 consul agent --server=false --client=0.0.0.0 --join 172.17.0.2
复制代码

第1个启动容器的IP一般是172.17.0.2,后边启动的几个容器IP会排着来:172.17.0.3、172.17.0.4、172.17.0.5。

这些Consul节点在Docker的容器内是互通的,他们通过桥接的模式通信。但是如果主机要访问容器内的网络,需要做端口映射。在启动第一个容器时,将Consul的8500端口映射到了主机的8900端口,这样就可以方便的通过主机的浏览器查看集群信息。

二、python服务注册

复制代码
#pip install python-consul
import consul

class Consul(object):
    def __init__(self, host, port):
        '''初始化,连接consul服务器'''
        self._consul = consul.Consul(host, port)

    def RegisterService(self, name, host, port, tags=None):
        tags = tags or []
        # 注册服务
        self._consul.agent.service.register(
            name,
            name,
            host,
            port,
            tags,
            # 健康检查ip端口,检查时间:5,超时时间:30,注销时间:30s
            check=consul.Check().tcp(host, port, "5s", "30s", "30s"))

    def GetService(self, name):
        services = self._consul.agent.services()
        service = services.get(name)
        if not service:
            return None, None
        addr = "{0}:{1}".format(service['Address'], service['Port'])
        return service, addr

if __name__ == '__main__':
    host="10.0.0.11" #consul服务器的ip
    port="8900" #consul服务器对外的端口
    consul_client=Consul(host,port)

    name="maple"
    host="10.0.0.11"
    port=8900
    consul_client.RegisterService(name,host,port)

    check = consul.Check().tcp(host, port, "5s", "30s", "30s")
    print(check)
    res=consul_client.GetService("maple")
    print(res)
复制代码
#执行效果
{'tcp': '10.0.0.11:8900', 'interval': '5s', 'timeout': '30s', 'DeregisterCriticalServiceAfter': '30s'}
({'ID': 'maple', 'Service': 'maple', 'Tags': [], 'Meta': {}, 'Port': 8900, 'Address': '10.0.0.11', 'Weights': {'Passing': 1, 'Warning': 1}, 'EnableTagOverride': False}, '10.0.0.11:8900')

通过10.0.0.11:8900访问注册后的效果

 

 

三、golang服务注册

复制代码
package main

import (
    "fmt"
    consul "github.com/hashicorp/consul/api"
    "strconv"
    "strings"
)

type Consul struct {
    consul *consul.Client
}

//服务发现 用来注册自己的服务端口给别的服务器调用和发现其他服务器
func InitConsul(host string, port int) (*Consul) {
    config := consul.DefaultConfig()
    config.Address = fmt.Sprintf("%s:%d", host, port)
    c, err := consul.NewClient(config)
    if err != nil {
        panic(err)
    }
    return &Consul{
        c,
    }

}

func (c *Consul) RegisterService(Name, Addr string, Port int, Tags ...string) error {
    return c.consul.Agent().ServiceRegister(&consul.AgentServiceRegistration{
        ID:      Name,
        Name:    Name,
        Port:    Port,
        Tags:    Tags,
        Address: Addr,
        Check: &consul.AgentServiceCheck{
            Timeout:                        "5s",
            Interval:                       "10s",
            TCP:                            fmt.Sprintf("%v:%v", Addr, Port, ),
            DeregisterCriticalServiceAfter: "30s",
        },
    })
}

func (c *Consul) GetService(Name string) (service *consul.AgentService, err error) {
    service, _, err = c.consul.Agent().Service(Name, &consul.QueryOptions{})
    return
}

func main() {
    var Consul *Consul
    //注册consul服务地址
    Host:="10.0.0.11"
    Port:=8900
    Server:="10.0.0.11:8900"
    Name:="go_maple"
    Consul = InitConsul(Host,Port)
    serverHost, err := strconv.Atoi(strings.Split(Server, ":")[1])
    if err != nil {
        panic(err)
    }
    err = Consul.RegisterService(Name,Host,serverHost)
    if err != nil {
        panic(err)
    }
    //获取服务
    res,err:=Consul.GetService("go_maple")
    if err != nil {
        panic(err)
    }
    fmt.Println(res)
}
复制代码

 

四、通过API的方式获取信息

复制代码
#http://10.0.0.11:8900/v1/health/service/maple

[
    {
        "Node": {
            "ID": "db46c9ad-5c8d-bb9b-0543-9edb48e7bccc",
            "Node": "71a1355e94b6",
            "Address": "172.17.0.2",
            "Datacenter": "dc1",
            "TaggedAddresses": {
                "lan": "172.17.0.2",
                "wan": "172.17.0.2"
            },
            "Meta": {
                "consul-network-segment": ""
            },
            "CreateIndex": 5,
            "ModifyIndex": 9
        },
        "Service": {
            "ID": "maple",
            "Service": "maple",
            "Tags": [],
            "Address": "10.0.0.11",
            "Meta": null,
            "Port": 8900,
            "Weights": {
                "Passing": 1,
                "Warning": 1
            },
            "EnableTagOverride": false,
            "ProxyDestination": "",
            "Proxy": {},
            "Connect": {},
            "CreateIndex": 4296,
            "ModifyIndex": 4296
        },
        "Checks": [
            {
                "Node": "71a1355e94b6",
                "CheckID": "serfHealth",
                "Name": "Serf Health Status",
                "Status": "passing",
                "Notes": "",
                "Output": "Agent alive and reachable",
                "ServiceID": "",
                "ServiceName": "",
                "ServiceTags": [],
                "Definition": {},
                "CreateIndex": 5,
                "ModifyIndex": 5
            },
            {
                "Node": "71a1355e94b6",
                "CheckID": "service:maple",
                "Name": "Service 'maple' check",
                "Status": "passing",
                "Notes": "",
                "Output": "TCP connect 10.0.0.11:8900: Success",
                "ServiceID": "maple",
                "ServiceName": "maple",
                "ServiceTags": [],
                "Definition": {},
                "CreateIndex": 4296,
                "ModifyIndex": 4297
            }
        ]
    }
]
复制代码
复制代码
#http://10.0.0.11:8900/v1/health/service/go_maple

[
    {
        "Node": {
            "ID": "db46c9ad-5c8d-bb9b-0543-9edb48e7bccc",
            "Node": "71a1355e94b6",
            "Address": "172.17.0.2",
            "Datacenter": "dc1",
            "TaggedAddresses": {
                "lan": "172.17.0.2",
                "wan": "172.17.0.2"
            },
            "Meta": {
                "consul-network-segment": ""
            },
            "CreateIndex": 5,
            "ModifyIndex": 9
        },
        "Service": {
            "ID": "go_maple",
            "Service": "go_maple",
            "Tags": [],
            "Address": "10.0.0.11",
            "Meta": null,
            "Port": 8900,
            "Weights": {
                "Passing": 1,
                "Warning": 1
            },
            "EnableTagOverride": false,
            "ProxyDestination": "",
            "Proxy": {},
            "Connect": {},
            "CreateIndex": 4725,
            "ModifyIndex": 4741
        },
        "Checks": [
            {
                "Node": "71a1355e94b6",
                "CheckID": "serfHealth",
                "Name": "Serf Health Status",
                "Status": "passing",
                "Notes": "",
                "Output": "Agent alive and reachable",
                "ServiceID": "",
                "ServiceName": "",
                "ServiceTags": [],
                "Definition": {},
                "CreateIndex": 5,
                "ModifyIndex": 5
            },
            {
                "Node": "71a1355e94b6",
                "CheckID": "service:go_maple",
                "Name": "Service 'go_maple' check",
                "Status": "passing",
                "Notes": "",
                "Output": "TCP connect 10.0.0.11:8900: Success",
                "ServiceID": "go_maple",
                "ServiceName": "go_maple",
                "ServiceTags": [],
                "Definition": {},
                "CreateIndex": 4725,
                "ModifyIndex": 4742
            }
        ]
    }
]
复制代码

 

 

posted on 2019-11-19 18:33  ExplorerMan  阅读(710)  评论(0编辑  收藏  举报

导航