目录

API文档与官网地址

Github

安装consul(基于Docker)

执行命令行

开放端口(Linux和服务器的防火墙规则)

浏览器输入服务器的IP地址与端口号(8500)访问consul的web界面

DNS发现服务 

安装工具bind-utils(Linux)

consul的API使用 

注册(健康监测)

1.被注册的服务提供IP和PORT信息,自定义被注册的服务的name和id信息;

2.被注册的服务需要基于consul标准的健康监测接口,IP:PORT/health

HTTP的方式调用API

使用Python调用consul的注册服务接口

编写被注册服务的健康检测接口(golang)

运行consul容器(在注册服务前需要先运行),运行python程序,运行golang程序 

GRPC的方式调用API

proto文件

使用Python调用consul的注册服务接口

编写被注册服务的健康检测(python)

运行consul容器(在注册服务前需要先运行),运行python注册服务程序,运行python健康检测程序 


API文档与官网地址

Service - Agent - HTTP API | Consul by HashiCorp


Github

GitHub - hashicorp/consul: Consul is a distributed, highly available, and data center aware solution to connect and configure applications across dynamic, distributed infrastructure.


安装consul(基于Docker)

执行命令行

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

开放端口(Linux和服务器的防火墙规则)

浏览器输入服务器的IP地址与端口号(8500)访问consul的web界面

python微服务发现和注册_python



DNS发现服务 

安装工具bind-utils(Linux)

yum install bind-utils
# 通过DNS命令发现服务
# IP地址:consul服务的IP地址
# 端口号:consul服务监听的端口号 
# 服务名:在consul服务中的服务名称
dig @IP地址 -p 端口号 服务名.service.consul SRV

consul的API使用 

注册(健康监测)

1.被注册的服务提供IP和PORT信息,自定义被注册的服务的name和id信息;

2.被注册的服务需要基于consul标准的健康监测接口,IP:PORT/health

:被注册服务应该与consul必须是可以互相访问的,否则注册的服务不可用

HTTP的方式调用API

使用Python调用consul的注册服务接口

注:通过python端将golang端的某个服务注册到consul,golang端被注册的服务编写健康检测接口,consul发送心跳到golang被注册的服务的健康检测接口,完成注册服务接口

import requests
headers = {
    "ContentType": "application/json"
}

def register(name, id, address, port):
    consul_host = "http://192.168.224.3:8500"
    url = consul_host + "/v1/agent/service/register"
    rsp = requests.put(url, headers=headers, json={
        "Name": name,
        "ID": id,
        "Tags": ["dong", "web"],
        "Address": address,
        "Port": port,
        "Check": {
            "HTTP":f"http://{address}:{port}/health",
            "Timeout":"5s",
            "Interval":"5s",
            "DeregisterCriticalServiceAfter":"5s"
        }
    })
    if rsp.status_code == 200:
        print(f"{address}:{port}--注册成功")
    else:
        print(f"{address}:{port}--注册失败,状态码:{rsp.status_code}")

if __name__ == '__main__':
    # register("mxshop-api-learn","mxshop-api-learn",address="127.0.0.1",port=8081)
    register("mxshop-api-learn","mxshop-api-learn",address="192.168.0.18",port=8081)

编写被注册服务的健康检测接口(golang)

Router := gin.Default()
// 定义服务注册(consul)的健康监测
Router.GET("/health", func(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"success": true,
	})
})

运行consul容器(在注册服务前需要先运行),运行python程序,运行golang程序 

python微服务发现和注册_IP_02

 

python微服务发现和注册_微服务_03


python微服务发现和注册_python微服务发现和注册_04



GRPC的方式调用API

注:python端注册自己的服务到consul,通过引入grpc包的健康检测接口,接收consul对服务的心跳,完成服务注册

proto文件

syntax = "proto3";

package grpc.health.v1;
option go_package = "./;proto";

message HealthCheckRequest {
  string service = 1;
}

message HealthCheckResponse {
  enum ServingStatus {
    UNKNOWN = 0;
    SERVING = 1;
    NOT_SERVING = 2;
    SERVICE_UNKNOWN = 3;  // Used only by the Watch method.
  }
  ServingStatus status = 1;
}

service Health {
  rpc Check(HealthCheckRequest) returns (HealthCheckResponse);

  rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse);
}

使用Python调用consul的注册服务接口

import requests
headers = {
    "ContentType": "application/json"
}

def register(name, id, address, port):
    consul_host = "http://192.168.224.3:8500"
    url = consul_host + "/v1/agent/service/register"
    rsp = requests.put(url, headers=headers, json={
        "Name": name,
        "ID": id,
        "Tags": ["dong", "web", "grpc"],
        "Address": address,
        "Port": port,
        "Check": {
            "GRPC": f"{address}:{port}",
            "GRPCUseTLS": False,  # 是否使用证书
            "Timeout": "5s",
            "Interval": "5s",
            "DeregisterCriticalServiceAfter": "5s"
        }
    })
    if rsp.status_code == 200:
        print(f"{address}:{port}--注册成功")
    else:
        print(f"{address}:{port}--注册失败,状态码:{rsp.status_code}")


if __name__ == '__main__':
    # register("mxshop-api-learn","mxshop-api-learn",address="127.0.0.1",port=8081)
    register("mxshop-api-learn", "mxshop-api-learn", address="192.168.0.18", port=8080)

编写被注册服务的健康检测(python)

# grpc_health.v1 文件来源
# health.proto文件内容在上文,通过命令行生成proto源码文件
https://github.com/grpc/grpc/tree/master/src/python/grpcio_health_checking/grpc_health/v1
# 安装grpc包
pip install grpcio
pip install grpcio-tools
import grpc
from concurrent import futures
from common.grpc_health.v1 import health_pb2, health_pb2_grpc
from common.grpc_health.v1 import health

def serve():
    # 实例化服务
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    # 注册健康监测
    health_pb2_grpc.add_HealthServicer_to_server(health.HealthServicer(), server)
    # 监听服务端口
    server.add_insecure_port("192.168.0.18:8080")
    # 开启服务
    server.start()

    server.wait_for_termination()

if __name__ == '__main__':
    serve()

运行consul容器(在注册服务前需要先运行),运行python注册服务程序,运行python健康检测程序