下面是一份 给予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()
部分运行结果如下: