python操作Redis

妖狐艹你老母 2022-03-08 07:44 259阅读 0赞

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

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

  1. pip install redis

上代码:

  1. class RedisOperate:
  2. def __init__(self, host='localhost', port=6379, db=0, password=None):
  3. self.rcon = redis.StrictRedis(host=host, port=int(port), db=int(db), password=password)
  4. def get_hash(self, name):
  5. hash_res = dict()
  6. if self.rcon.hgetall(name):
  7. for subkey, sub_value in self.rcon.hgetall(name).items():
  8. hash_res[subkey.decode()] = sub_value.decode()
  9. return hash_res
  10. def _insert_hash(self, hash_json=None):
  11. self.rcon.hmset(hash_json.get("hkey"), hash_json.get("field_value"))
  12. def excute_command(self, *args, **kwargs):
  13. # logger.info("Command:{0}".format(args))
  14. return self.rcon.execute_command(*args, **kwargs)
  15. if __name__ == '__main__':
  16. RO = RedisOperate(host="X.X.X.X", port=6300, db=2, password='XXX')
  17. # 获取某个key的值
  18. res = RO.excute_command('GET', 'kn.simcard.action.recommend.2E1269D7-28B9-4B88-B7F4-EEF3E2DF70C4:bits')
  19. # list类型数据结构操作
  20. ro_res = RO.excute_command("LPUSH", "com.dev.sys.recommend.productList",
  21. "{'available':true,'buttonName':'立即还款','infoName1':'利率'")
  22. print(ro_res)
  23. ro_res00 = RO.excute_command("LREM", "com.dev.sys.recommend.recConfList", 0,
  24. "{'available': true,'client': 1,'createTime': 1519874614000,'effectiveTime': 1517241600000}")
  25. ro_res11 = RO.excute_command('LRANGE', 'com.dev.sys.recommend.recConfList', 0, -1)
  26. for index in range(len(ro_res11)):
  27. print(ro_res11[index].decode())
  28. # SET类型数据结构操作
  29. print(RO.excute_command('SMEMBERS', 'kn:simcard:exposure:20180420012:2018-04-25'))
  30. RO.excute_command('SADD', 'kn:simcard:exposure:20180420012:2018-04-25', 'hello:123', 'world:123')
  31. RO.excute_command('SREM', 'kn:simcard:exposure:20180420017:2018-05-03', 'chaojidai:1')
  32. print(RO.excute_command('type', 'com.dev.sys.recommend.recConfList'))
  33. # 查询所有的key
  34. ro_res = RO.excute_command('KEYS', '*')
  35. print(ro_res)
  36. #刪除key
  37. # ro_res = RO.excute_command('DEL', 'kn:simcard:exposure:20180420012:2018-04-25', 1)
  38. # hash类型数据结构操作
  39. ro_res = RO.excute_command('HGET', 'kn.simcard.action.recommend.deviceId-868515037202859-generate-cardniu.2018-05-31')
  40. print(ro_res)

发表评论

表情:
评论列表 (有 0 条评论,259人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python操作Redis

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