class MonitorClient(object): def __init__(self): self.redis = RedisHelper() self.configs = {} @staticmethod def format_msg(key, value): msg = {key: value} return pickle.dumps(msg) def get_configs(self): configs = self.redis.get('HostConfig:%s' % client_ip) if configs: self.configs = pickle.loads(configs) return True def handle(self): if self.get_configs(): while True: for service_name, config_value in self.configs.items(): interval, plugin, last_time = config_value if time.time() - last_time > interval: a = threading.Thread(target=self.task, args=[service_name, plugin]) a.start() self.configs[service_name][2] = time.time() else: wait_time = interval - (time.time() - last_time) print '%s will run in %s seconds' % (service_name, wait_time) time.sleep(1) else: print '--- could not find the monitor configure ---' def task(self, service_name, plugin_name): print '--- Going to handle the %s task ---' % service_name func = getattr(plugins_api, plugin_name) res = func() print "\033[1;32m%s\033[0m" % res # 拼接出传递的数据 msg = self.format_msg('report', { 'ip': client_ip, 'service_name': service_name, 'info_data': res }) self.redis.publish(msg) def run(self): print '--- start Monitor Client ---' self.handle()
from redis_helper import RedisHelper obj = RedisHelper() obj.publish('hello world') print 1
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'luotianshuai' from redis_helper import RedisHelper obj = RedisHelper() #实例化方法 obj.publish('hello') #执行发布
from redis_helper import RedisHelper import datetime import base64 import time_utils publish = RedisHelper() # publish.publish('hello world.') with open('robots.jpg', 'rb') as image_file: image_bytes = image_file.read() d = datetime.datetime.now() # encoded = base64.b64encode(image_bytes).decode('ascii') # publish.publish(encoded) # 读取的文件的编码居然是ISO-8859-1, 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte publish.publish(str(image_bytes, encoding='ISO-8859-1')) # 字节数组转str?时间上跟b64encode差不多 time_utils.millis(datetime.datetime.now(), d)