• 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
                }
            ]
        }
    ]
    复制代码
     
  • 相关阅读:
    什么是首次适应算法,该算法的特点是什么?
    用上、下界防护方法是如何实现界地址保护?在硬件上需要什么支持?
    什么是存储保护?
    什么是静态地址重定位,它需要什么支持?什么是动态地址重定位,他需要什么支持?静态地址重定位与动态地址重定位有什么区别?
    什么是逻辑地址,什么是物理地址,为什么要进行二者的转换工作?
    三个进程共享四个同类资源,这些资源的分配与释放只能一次一个。已知每一个进程最多需要两个资源,试问,该系统会发生死锁吗?为什么?
    试举出一种一种避免死锁的发生的方法,并说明为什么能避免死锁的发生?
    产生死锁的原因是什么?产生死锁的必要条件是什么?
    什么是死锁,试举例说明?
    说出两种一笔调度的算法,并说出这两种移臂调度算法的定义。
  • 原文地址:https://www.cnblogs.com/ExMan/p/11891398.html
Copyright © 2020-2023  润新知