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
            }
        ]
    }
]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM