1、安装
1 2 3 4
| # 安装 docker run -d -p 8500:8500 -p 8300:8300 -p 8301:8301 -p 8302:8302 -p 8600:8600/udp consul consul agent -dev -client=0.0.0.0 # 开机自启 docker container update --restart=always 容器id/名字
|
2、访问
安装完成后访问ip+8500
端口,如果正常打开成功。
3、基本使用
注册
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import requests
headers = { "contentType": "application/json" }
def register(name, id, address, port): js_data = { "Name": name, "ID": id, "Tags": ["web", "python", "js"], "Address": address, "Port": port } url = "http://ip:8500/v1/agent/service/register" req = requests.put(url, headers=headers, json=js_data) if req.status_code == 200: print("注册成功") else: print(f"注册失败: {req.status_code}")
if __name__ == '__main__': register("lenkyes", "len666", "服务ip", 50051)
|
成功注册如下图
注销
1 2 3 4 5 6 7 8
| def deregister(id): url = f"http://ip:8500/v1/agent/service/deregister/{id}" req = requests.put(url, headers=headers) if req.status_code == 200: print("注销成功") else: print(f"注销失败:{req.status_code}")
|
健康检查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| def health_register(name, id, address, port): js_data = { "Name": name, "ID": id, "Tags": ["web", "python", "js"], "Address": address, "Port": port, "Check": { "HTTP": f"http://{address}:{port}/health", "Timeout": "5s", "Interval": "5s", "DeregisterCriticalServiceAfter": "20s" } } url = "http://ip:8500/v1/agent/service/register" req = requests.put(url, headers=headers, json=js_data) if req.status_code == 200: print("注册成功") else: print(f"注册失败: {req.status_code}")
|
Timeout:超时时间
Interval:多长时间检查一次
DeregisterCriticalServiceAfter:如果没检查到报错,则多少秒后从注册中心注销掉
配置GRPC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| def GRPC_register(name, id, address, port): js_data = { "Name": name, "ID": id, "Tags": ["web", "python", "js"], "Address": address, "Port": port, "Check": { "GRPC": f"{address}:{port}", "GRPCUseTLS": False, "Timeout": "5s", "Interval": "5s", "DeregisterCriticalServiceAfter": "15s" } } url = "http://ip:8500/v1/agent/service/register" req = requests.put(url, headers=headers, json=js_data) if req.status_code == 200: print("注册成功") else: print(f"注册失败: {req.status_code}")
|
GRPCUseTLS:False不认证证书
GRPC:grpc服务地址和端口
过滤
1 2 3 4 5 6 7
| def filter_service(name): url = "http://ip:8500/v1/agent/services" params = { "filter": f'Service == "{name}"' } rsp = requests.get(url, params=params).json() print(rsp)
|