python-consul-分布式配置代码

下面是一份 给予consul作为分布式配置的python代码:

class LyConf(object):

    def __init__(self, consul_key, consul_client=None, host='127.0.0.1',
                 port=8500, loop_interval=5):
        if consul_client:
            self.consul_client = consul_client
        else:
            self.consul_client = consul.Consul(host, port)
        self._conf = {}
        self.consul_key = consul_key
        self.consul_key_index = None
        self.loop_interval = loop_interval
        self.should_stop = Event()
        self._sync_conf()

    def __getitem__(self, item):
        return self._conf.get(item)

    def __setitem__(self, key, value):
        conf = copy.deepcopy(self._conf)
        conf[key] = value
        conf_str = json.dumps(conf)
        ret = self.consul_client.kv.put(self.consul_key, conf_str)
        if ret:
            self._conf = conf

    def __delattr__(self, item):
        conf = copy.deepcopy(self._conf)
        del conf[item]
        conf_str = json.dumps(conf)
        ret = self.consul_client.kv.put(self.consul_key, conf_str)
        if ret:
            self._conf = conf

    def _sync_conf(self):
        curr_index = self.consul_key_index
        index, val = self.consul_client.kv.get(self.consul_key, curr_index)
        print('val', val)
        if curr_index != index:
            self.consul_key_index = index
            if val:
                body = val.get('Value')
                if body is not None:
                    conf = json.loads(body)
                    self._conf = conf

    def run(self):
        while True:
            # sleep for `sleep_time`, unless `should_stop` fires, in which
            # case we leave the while loop and stop entirely
            with Timeout(self.loop_interval, exception=False):
                self.should_stop.wait()
                break
            self._sync_conf()

    def stop(self):
        self.should_stop.send()

    def wait(self):
        self.should_stop.wait()

测试代码如下:


from consul_lib.consul_lib import LyConf
import eventlet

eventlet.monkey_patch()

lyconf = LyConf('test',host='172.18.0.11')

eventlet.spawn_n(lyconf.run)
runnlet = eventlet.spawn(lyconf.wait)

def test_set():
    idx = 1
    while (True):
        eventlet.sleep(3)
        print('lyconf:', lyconf._conf)
        k = 'x' + str(idx)
        lyconf[k] = idx
        idx += 1

def test_get():
    while (True):
        eventlet.sleep(3)
        print('lyconf:', lyconf._conf)

test_get()

部分运行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值