1 安装
(1) docker拉取consul镜像
docker pull consul
(2) 运行consul容器
docker run -d —name=consul —restart=always -p 8500:8500 -p 8300:8300 -p 8301:8301 -p 8302:8302 -p 8600:8600/udp consul:latest agent -dev -client=0.0.0.0
端口详解
- 8500 : http 端口,用于 http 接口和 web ui访问;
- 8300 : server rpc 端口,同一数据中心 consul server 之间通过该端口通信
- 8301 : serf lan 端口,同一数据中心 consul client 通过该端口通信; 用于处理当前datacenter中LAN的gossip通信
- 8302 : serf wan 端口,不同数据中心 consul server 通过该端口通信; agent Server使用,处理与其他datacenter的gossip通信;
- 8600 : dns 端口,用于已注册的服务发现;
2 访问后台
http://192.168.1.103:8500/dig @192.168.1.103 -p 8600 consul.service.consul SRV
3 py服务注册
consul_api.py
import requests
headers = {
"contentType": "application/json"
}
BASE_URL = "http://127.0.0.1:8500"
def register_http(name, id, address, port, *tags):
url = f"{BASE_URL}/v1/agent/service/register"
rsp = requests.put(url=url, headers=headers, json={
"Name": name,
"ID": id,
"Address": address,
"Port": port,
"Tags": tags,
"Check": { # 健康检查
"HTTP": f"http://{address}:{port}/health",
"Timeout": "5s",
"Interval": "5s",
"DeregisterCriticalServiceAfter": "15s",
}
})
if rsp.status_code == 200:
print("注册成功")
else:
print(f"注册失败: {rsp.status_code}")
def register_grpc(name, id, address, port, *tags):
url = f"{BASE_URL}/v1/agent/service/register"
rsp = requests.put(url=url, headers=headers, json={
"Name": name,
"ID": id,
"Address": address,
"Port": port,
"Tags": tags,
"Check": { # 健康检查
"GRPC": f"{address}:{port}",
"GRPCUseTLS": False,
"Timeout": "5s",
"Interval": "5s",
"DeregisterCriticalServiceAfter": "15s",
}
})
if rsp.status_code == 200:
print("注册成功")
else:
print(f"注册失败: {rsp.status_code}")
def deregister(id):
url = f"{BASE_URL}/v1/agent/service/deregister/{id}"
rsp = requests.put(url, headers=headers)
if rsp.status_code == 200:
print("注销成功")
else:
print(f"注销失败: {rsp.status_code}")
def filter_service(name):
url = f"{BASE_URL}/v1/agent/services"
params = {
"filter": f'Service == "{name}"'
}
rsp = requests.get(url, params=params).json()
for key, value in rsp.items():
print(key)
print(rsp)
if __name__ == '__main__':
register_http("user_api", "user_api", "192.168.1.103", 8021)
register_grpc("user_srv", "user_srv", "192.168.1.103", 50051)
# deregister("mxshop_srv")
# filter_service("mxshop_srv")
4 go服务注册
package main
import (
"fmt"
"github.com/hashicorp/consul/api"
)
func RegisterHttp(name string, id string, address string, port int, tags []string) error {
cfg := api.DefaultConfig()
cfg.Address = fmt.Sprintf("%s:%d", address, 8500)
client, err := api.NewClient(cfg)
if err != nil {
panic(err)
}
// 生成对应的检查对象
check := &api.AgentServiceCheck{
HTTP: fmt.Sprintf("http://%s:%d/health", address, port),
Timeout: "5s",
Interval: "5s",
DeregisterCriticalServiceAfter: "10s",
}
// 生成注册对象
registration := new(api.AgentServiceRegistration)
registration.Name = name
registration.ID = id
registration.Port = port
registration.Tags = tags
registration.Check = check
err = client.Agent().ServiceRegister(registration)
if err != nil {
fmt.Println(err.Error())
panic(err)
}
return nil
}
func AllServices() {
// 获取所有服务
cfg := api.DefaultConfig()
cfg.Address = "192.168.1.103:8500"
client, err := api.NewClient(cfg)
if err != nil {
panic(err)
}
data, err := client.Agent().Services()
if err != nil {
panic(err)
}
for key, _ := range data {
fmt.Println(key)
}
}
func FilterService() {
cfg := api.DefaultConfig()
cfg.Address = "192.168.1.103:8500"
client, err := api.NewClient(cfg)
if err != nil {
panic(err)
}
data, err := client.Agent().ServicesWithFilter(`Service == "user_srv"`)
if err != nil {
panic(err)
}
for key, _ := range data {
fmt.Println(key)
}
}
func main() {
//_ = RegisterHttp("user_api2", "user_api2", "192.168.1.103", 8021, []string{"mxshop"})
//AllServices()
FilterService()
}