天天看點

Python3 使用 consul 作為微服務的注冊中心

微服務的注冊中心有很多,常用的有

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

Python3 使用 consul 作為微服務的注冊中心
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
           
Python3 使用 consul 作為微服務的注冊中心

參考文章:https://www.cnblogs.com/angelyan/p/11157176.html#_label3