微服务的注册中心有很多,常用的有 Euerka
、Zookeeper
、Nacos
、Consul
等等,我们使用 Consul
作为微服务的注册中心。
启动 Consul
我们先在本地搭建一个单点的 Consul
服务(在生产环境中一定是高可用集群)。
先从 Consul
官网:https://www.consul.io 下载 Consul
,然后启动即可:
./consul agent -dev
也可以指定参数
./consul agent -dev -client 0.0.0.0 -ui
启动:
MacBook:Downloads zhangyi$ ./consul agent -dev -client 0.0.0.0 -ui
==> Starting Consul agent...
Version: '1.10.1'
Node ID: '7083441d-403c-5ae4-39ed-3d43eb8baf0b'
Node name: 'MacBook'
Datacenter: 'dc1' (Segment: '<all>')
Server: true (Bootstrap: false)
Client Addr: [0.0.0.0] (HTTP: 8500, HTTPS: -1, gRPC: 8502, DNS: 8600)
Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false, Auto-Encrypt-TLS: false
==> Log data will now stream in as it occurs:
......
将服务注册到 Consul 中
官方为 Consul 提供了两个 Python 包,我们直接安装最新的 python-consul2
。
pip install python-consul2
安装好之后就可以使用 consul 包进行注册服务了:
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import consul
# 初始化 Consul 服务
cursor = consul.Consul(host='127.0.0.1', port=8500)
# 注册服务到 Consul
cursor.agent.service.register(
name='test-service', address='127.0.0.1', port=5000,
# 心跳检查:间隔:5s,超时:30s,注销:30s
check=consul.Check().tcp('127.0.0.1', 5000, '5s', '30s', '30s')
)
# 获取服务状态
checks = cursor.agent.checks()
status = checks.get('service:test-service').get('Status')
print(status)
# 获取服务
services = cursor.agent.services()
service = '%s:%s' % (services.get('test-service').get('Address'), services.get('test-service').get('Port'))
print(service)
# 添加 kv 数据
result = cursor.kv.put('key', 'test-value')
print(result)
# 获取 kv 数据
_, result = cursor.kv.get('key')
result = result.get('Value').decode('utf-8')
print(result)
执行结果:
(demo) MacBook:demo zhangyi$ python consul_demo.py
critical
127.0.0.1:5000
True
test-value
参考文章:https://www.cnblogs.com/angelyan/p/11157176.html#_label3