pyton操作Redis

使用redis模块,可以方便的使用脚本完成Redis数据构造和清理。本文借助脚本,给大家演示一下redis常用数据结构list、set、hash等数据结构的常用增删改查的操作。其他命令可以参考:

Redis 命令参考:http://doc.redisfans.com/

pip install redis

上代码:

class RedisOperate:
    def __init__(self, host='localhost', port=6379, db=0, password=None):
        self.rcon = redis.StrictRedis(host=host, port=int(port), db=int(db), password=password)

    def get_hash(self, name):
        hash_res = dict()
        if self.rcon.hgetall(name):
            for subkey, sub_value in self.rcon.hgetall(name).items():
                hash_res[subkey.decode()] = sub_value.decode()
        return hash_res

    def _insert_hash(self, hash_json=None):
        self.rcon.hmset(hash_json.get("hkey"), hash_json.get("field_value"))

    def excute_command(self, *args, **kwargs):
        # logger.info("Command:{0}".format(args))
        return self.rcon.execute_command(*args, **kwargs)


if __name__ == '__main__':
    RO = RedisOperate(host="X.X.X.X", port=6300, db=2, password='XXX')
    # 获取某个key的值
    res = RO.excute_command('GET', 'kn.simcard.action.recommend.2E1269D7-28B9-4B88-B7F4-EEF3E2DF70C4:bits')

    # list类型数据结构操作
    ro_res = RO.excute_command("LPUSH", "com.dev.sys.recommend.productList",
                               "{'available':true,'buttonName':'立即还款','infoName1':'利率'")
    print(ro_res)
    ro_res00 = RO.excute_command("LREM", "com.dev.sys.recommend.recConfList", 0,
                                 "{'available': true,'client': 1,'createTime': 1519874614000,'effectiveTime': 1517241600000}")
    ro_res11 = RO.excute_command('LRANGE', 'com.dev.sys.recommend.recConfList', 0, -1)
    for index in range(len(ro_res11)):
        print(ro_res11[index].decode())

    # SET类型数据结构操作
    print(RO.excute_command('SMEMBERS', 'kn:simcard:exposure:20180420012:2018-04-25'))
    RO.excute_command('SADD', 'kn:simcard:exposure:20180420012:2018-04-25', 'hello:123', 'world:123')
    RO.excute_command('SREM', 'kn:simcard:exposure:20180420017:2018-05-03', 'chaojidai:1')
    print(RO.excute_command('type', 'com.dev.sys.recommend.recConfList'))
    
    # 查询所有的key
    ro_res = RO.excute_command('KEYS', '*')
    print(ro_res)
    
    #刪除key
    # ro_res = RO.excute_command('DEL', 'kn:simcard:exposure:20180420012:2018-04-25', 1)

    # hash类型数据结构操作
    ro_res = RO.excute_command('HGET', 'kn.simcard.action.recommend.deviceId-868515037202859-generate-cardniu.2018-05-31')
    print(ro_res)

猜你喜欢

转载自blog.csdn.net/a200822146085/article/details/88556935