濮阳杆衣贸易有限公司

主頁 > 知識庫 > Python 使用 consul 做服務(wù)發(fā)現(xiàn)示例詳解

Python 使用 consul 做服務(wù)發(fā)現(xiàn)示例詳解

熱門標簽:400電話 申請 條件 云南地圖標注 汕頭電商外呼系統(tǒng)供應(yīng)商 北京外呼電銷機器人招商 鄭州智能外呼系統(tǒng)中心 電銷機器人 金倫通信 crm電銷機器人 賓館能在百度地圖標注嗎 南京crm外呼系統(tǒng)排名

前言

前面一章講了微服務(wù)的一些優(yōu)點和缺點,那如何做到

一、目標

二、使用步驟

1. 安裝 consul

我們可以直接使用官方提供的二進制文件來進行安裝部署,其官網(wǎng)地址為 https://www.consul.io/downloads

下載后為可執(zhí)行文件,在我們開發(fā)試驗過程中,可以直接使用 consul agent -dev 命令來啟動一個單節(jié)點的 consul

在啟動的打印日志中可以看到 agent: Started HTTP server on 127.0.0.1:8500 (tcp), 我們可以在瀏覽器直接訪問 127.0.0.1:8500 即可看到如下

這里我們的 consul 就啟動成功了

2. 服務(wù)注冊

在網(wǎng)絡(luò)編程中,一般會提供項目的 IP、PORT、PROTOCOL,在服務(wù)治理中,我們還需要知道對應(yīng)的服務(wù)名、實例名以及一些自定義的擴展信息

在這里使用 ServiceInstance 接口來規(guī)定注冊服務(wù)時必須的一些信息

class ServiceInstance:

 def __init__(self, service_id: str, host: str, port: int, secure: bool = False, metadata: dict = None,
   instance_id: str = None):
 self.service_id = service_id
 self.host = host
 self.port = port
 self.secure = secure
 self.metadata = metadata
 self.instance_id = instance_id

 def get_instance_id(self):
 return

定義基類

在上面規(guī)定了需要注冊的服務(wù)的必要信息,下面定義下服務(wù)注冊和剔除的方法,方便以后實現(xiàn) Eureka 和 Redis 的方式

import abc


class ServiceRegistry(abc.ABC):

 @abc.abstractmethod
 def register(self, service_instance: ServiceInstance):
 pass

 @abc.abstractmethod
 def deregister(self):
 pass

具體實現(xiàn)

因為 consul 提供了 http 接口來對consul 進行操作,我們也可以使用 http 請求方式進行注冊和剔除操作,具體 http 接口文檔見 https://www.consul.io/api-docs, consul 并沒有提供 Python 語言的實現(xiàn),這里使用 python-consul 來訪問 consul

import consul


class ConsulServiceRegistry(ServiceRegistry):
 _consul = None
 _instance_id = None

 def __init__(self, host: str, port: int, token: str = None):
 self.host = host
 self.port = port
 self.token = token
 self._consul = consul.Consul(host, port, token=token)

 def register(self, service_instance: ServiceInstance):
 schema = "http"
 if service_instance.secure:
  schema = "https"
 check = consul.Check.http(f'{schema}:{service_instance.host}:{service_instance.port}/actuator/health', "1s",
     "3s", "10s")
 self._consul.agent.service.register(service_instance.service_id,
      service_id=service_instance.instance_id,
      address=service_instance.host,
      port=service_instance.port,
      check=check)
 self._instance_id = service_instance.instance_id

 def deregister(self):
 if self._instance_id:
  self._consul.agent.service.deregister(service_id=self._instance_id)
  self._instance_id = None

3. 服務(wù)發(fā)現(xiàn)

在服務(wù)發(fā)現(xiàn)中,一般會需要兩個方法

  • 獲取所有的服務(wù)列表
  • 獲取指定的服務(wù)的所有實例信息

基類定義

import abc


class DiscoveryClient(abc.ABC):

 @abc.abstractmethod
 def get_services(self) -> list:
 pass

 @abc.abstractmethod
 def get_instances(self, service_id: str) -> list:
 pass

具體實現(xiàn)

來實現(xiàn)一下

這里是簡化版,所以一些參數(shù)直接寫死了,如果需要可以適當修改

import consul


class ConsulServiceDiscovery(DiscoveryClient):

 _consul = None

 def __init__(self, host: str, port: int, token: str = None):
 self.host = host
 self.port = port
 self.token = token
 self._consul = consul.Consul(host, port, token=token)

 def get_services(self) -> list:
 return self._consul.catalog.services()[1].keys()

 def get_instances(self, service_id: str) -> list:
 origin_instances = self._consul.catalog.service(service_id)[1]
 result = []
 for oi in origin_instances:
  result.append(ServiceInstance(
  oi.get('ServiceName'),
  oi.get('ServiceAddress'),
  oi.get('ServicePort'),
  oi.get('ServiceTags'),
  oi.get('ServiceMeta'),
  oi.get('ServiceID'),
  ))
 return result

4. 測試用例

import unittest
from random import random

class MyTestCase(unittest.TestCase):
 def test_consul_register(self):
 instance = ServiceInstance("abc", "127.0.0.1", 8000, instance_id=f'abc_{random()}')

 registry = ConsulServiceRegistry("127.0.0.1", 8500)
 discovery = ConsulServiceDiscovery("127.0.0.1", 8500)
 registry.register(instance)
 print(discovery.get_services())
 print(discovery.get_instances("abc"))
 self.assertEqual(True, True)
if __name__ == '__main__':
 unittest.main()

總結(jié)

通過使用 consul api 我們可以簡單的實現(xiàn)基于 consul 的服務(wù)發(fā)現(xiàn),在通過結(jié)合 http rpc 就可簡單的實現(xiàn)服務(wù)的調(diào)用,下面一章來簡單講下 go 如何發(fā)起 http 請求,為我們做 rpc 做個鋪墊

具體代碼見 https://github.com/zhangyunan1994/gimini

參考

https://www.consul.io/api-docs

https://github.com/hashicorp/consul/tree/master/api

到此這篇關(guān)于Python 使用 consul 做服務(wù)發(fā)現(xiàn)的文章就介紹到這了,更多相關(guān)Python 使用 consul 服務(wù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python實現(xiàn)FTP文件傳輸?shù)姆椒ǎǚ?wù)器端和客戶端)
  • python實現(xiàn)從ftp服務(wù)器下載文件
  • Python3搭建http服務(wù)器的實現(xiàn)代碼
  • python+selenium定時爬取丁香園的新型冠狀病毒數(shù)據(jù)并制作出類似的地圖(部署到云服務(wù)器)

標簽:浙江 石家莊 昆明 懷化 文山 錫林郭勒盟 梅州 西寧

巨人網(wǎng)絡(luò)通訊聲明:本文標題《Python 使用 consul 做服務(wù)發(fā)現(xiàn)示例詳解》,本文關(guān)鍵詞  Python,使用,consul,做,服務(wù),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Python 使用 consul 做服務(wù)發(fā)現(xiàn)示例詳解》相關(guān)的同類信息!
  • 本頁收集關(guān)于Python 使用 consul 做服務(wù)發(fā)現(xiàn)示例詳解的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    石首市| 二连浩特市| 扬州市| 花莲县| 南投市| 盐山县| 南陵县| 吴川市| 开原市| 红桥区| 象州县| 鄢陵县| 霍山县| 隆林| 廉江市| 文登市| 邢台县| 卫辉市| 富宁县| 阳曲县| 潼关县| 汉川市| 阿克陶县| 达拉特旗| 缙云县| 宁明县| 临清市| 南溪县| 类乌齐县| 新巴尔虎右旗| 封开县| 锡林浩特市| 衡南县| 宜春市| 怀远县| 寿阳县| 九龙城区| 扶沟县| 白水县| 合肥市| 库尔勒市|