def setRedisValue(self, key, value, valueType=None, channel="uc", ttl=None): """ 设置redis值和value :param key: :param value: :param valueType: set string list hash :param channel: uc 用户中心 、nc消息中心 :return: """ try: if cb.can_not_do_byEnv(): return except: logging.error("无法读取Env环境参数") r = self.getRedisInstance(channel=channel) try: if valueType is None or valueType.lower() == "string": result = r.set(key, str(value), ex=ttl) elif valueType.lower() == "json": result = r.set(key, json.dumps(value), ex=ttl) elif valueType.lower() == "hash": for iKey, iValue in value.items(): result = r.hset(key, iKey, iValue) logging.info("redis设置hset操作:key={0}成功{1},返回{2}".format( key, iKey, result)) if ttl != None: result = r.expire(key, ttl) logging.info("redis设置hset的expire操作:key={0}成功,返回{1}".format( key, result)) return elif valueType.lower() == "list": for iValue in value: result = r.lpush(key, iValue) logging.info("redis设置lpush操作:key={0}成功{1},返回{2}".format( key, iValue, result)) if ttl != None: result = r.expire(key, ttl) logging.info( "redis设置lpush的expire操作:key={0}成功,返回{1}".format( key, result)) return logging.info("redis设置value操作:key={0}成功,返回{1}".format(key, result)) except Exception as e: logging.error(e)
def delRedisValue(self, key): try: if cb.can_not_do_byEnv(): return except: logging.error("无法读取Env环境参数") try: _key = key.strip() _resp_code = self.client.delete(_key) resp = "成功!!" if _resp_code == 1 else "失败!!" logging.debug("redis 删除key={0}, 结果{1}".format(_key, resp)) except Exception as e: logging.error(e)
def getRedisValue(self, key, valueType=None, channel="uc"): """ 获取redis存储的值 :param key: :param channel:uc 用户中心 、nc消息中心 :param type: 获取的消息类型 默认为None, string, json, hash,list :return: """ try: if cb.can_not_do_byEnv(): return except: logging.error("无法读取Env环境参数") r = self.getRedisInstance(channel=channel) logging.info("开始操作redis") try: logging.info("读取key={0},valueType={1}, channel={2}".format( key, valueType, channel)) if valueType == None or valueType.lower() == "string": result = str(r.get(key)) elif valueType.lower() == "json": result = json.loads(r.get(key)) elif valueType.lower() == "hash": result = dict(r.hgetall(key)) elif valueType.lower() == "list": result = list(r.lrange(key, 0, -1)) elif valueType.lower() == "zset": result = list(r.zrange(key, 0, -1)) elif valueType.lower() == "nset": # 普通set result = list(r.smembers(key)) else: result = None logging.info("读取redis的值={0}".format(result)) return result except Exception as e: logging.error(e)
def delRedisValue(self, key, channel="uc"): """ 删除redis中的key :param key: :param channel:uc 用户中心 、nc消息中心 :return: """ try: if cb.can_not_do_byEnv(): return except: logging.error("无法读取Env环境参数") redisConfig = self.getRedisConfig(channel=channel) redisHost = redisConfig["host"] redisPort = redisConfig["port"] redisDb = redisConfig["db"] r = redis.Redis(host=redisHost, port=redisPort, db=redisDb) try: return r.delete(key) except Exception as e: logging.error(e)