import random
import time
from threading import Timer
import etcd3
from utils import config_etcd
class ETCDClient:
def __init__(self, host, port, ttl, name):
self.name = name
self.ttl = ttl
self.cli = etcd3.client(host, port)
self.lease_id = random.randint(1,100000)
while self.cli.get_lease_info(self.lease_id).TTL != -1:
self.lease_id = random.randint(1,100000)
self.timer = None
def keep_alive(self):
res = self.cli.refresh_lease(self.lease_id)
print(list(res))
self.timer = Timer(self.ttl - 1, self.keep_alive)
self.timer.start()
def put(self, key, value):
if self.cli.get_lease_info(self.lease_id).TTL == -1:
self.cli.lease(self.ttl, self.lease_id)
self.keep_alive()
self.cli.put(key, value, self.lease_id)
def get(self, key):
value, meta = self.cli.get(key)
value = value.decode('utf-8')
return value
def get_service(self):
entities = self.cli.get_prefix(f"/{self.name}/v1")
return [entity[1].key.decode('utf-8') for entity in entities]
def __del__(self):
if self.timer is not None:
self.timer.cancel()
self.cli.revoke_lease(self.lease_id)
self.cli.close()
client = ETCDClient(**config_etcd)
#if __name__ == '__main__':
# client.put("d", "2")
# client.put("a", "2")
# client.put("c", "2")
# print(client.get("c"))
python+etcd服务发现与注册工具类
最新推荐文章于 2024-09-07 20:08:36 发布