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

一、安装启动consul

1.通过docker快速安装

#获取docker镜像

docker pull consul

2.启动consul

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

copycode.gif

#启动第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

copycode.gif

第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服务注册

copycode.gif

#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="" #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)

copycode.gif

#执行效果

{'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访问注册后的效果

L3Byb3h5L2h0dHBzL2ltZzIwMTguY25ibG9ncy5jb20vYmxvZy8xNDQ5MTQ3LzIwMTkwNy8xNDQ5MTQ3LTIwMTkwNzA5MTQzMTQ2MzM0LTk0MjQ2OTk5MC5wbmc=.jpg

L3Byb3h5L2h0dHBzL2ltZzIwMTguY25ibG9ncy5jb20vYmxvZy8xNDQ5MTQ3LzIwMTkwNy8xNDQ5MTQ3LTIwMTkwNzA5MTQzMzMzODA3LTE5NDM4MDg4NDcucG5n.jpg

三、golang服务注册

copycode.gif

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)

}

copycode.gif

L3Byb3h5L2h0dHBzL2ltZzIwMTguY25ibG9ncy5jb20vYmxvZy8xNDQ5MTQ3LzIwMTkwNy8xNDQ5MTQ3LTIwMTkwNzA5MTUxNDE4MjgzLTE1NDA0OTkzMi5wbmc=.jpg

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

copycode.gif

#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

}

]

}

]

copycode.gif

copycode.gif

#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

}

]

}

]

copycode.gif

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值