Python redis模块详解

Posted cuisi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python redis模块详解相关的知识,希望对你有一定的参考价值。

在使用 Redis、Codis 时,我们经常需要做一些批量操作,通过连接数据库批量对 key 进行操作:

常见的场景:

  1.批量扫描key

  2.获取info信息

  3.获取client信息

  4.设置配置参数

  5.redis定期扫描

批量初始化redis 客户端:

 1 from redis import Redis
 2 def setExpiredKeys():
 3     try:
 4         if redis_pass == none:
 5             redisclient = Redis(host=redis_host, port=redis_port,db=0)
 6         else:
 7             redisclient = Redis(host=redis_host, port=redis_port, password=redis_pass)
 8         # 初始化 redis 客户端:redisclient
 9         # info = redisclient.info()
10 
11     except Exception as e:
12         raise e
13 if __name__ == __main__:
14     redis_host = 39.196.9.99
15     redis_port = 6001
16     redis_pass = 123456
17     setExpiredKeys()

 

详解:

1. Redis.info() 源代码:

  返回结果:包含相关信息的字典

1 def info(self, section=None):
2 """
3 Returns a dictionary containing information about the Redis server
4 """
5 if section is None:
6     return self.execute_command(INFO)
7 else:
8     return self.execute_command(INFO, section)
1 info = redisclient.info()            # 返回 Redis Server Info的所有信息
2 info = redisclient.info(Keyspace)  # 返回指定section的信息    
1 output:
2 {db0: {keys: 20005, expires: 5322, avg_ttl: 84036169}}

 

2. Redis.get() 源代码

  获取key的value

1 def get(self, name):
2         """
3         Return the value at key ``name``, or None if the key doesnt exist
4         """
5         return self.execute_command(GET, name)
1 info = redisclient.get(name)     # 返回value:Jack

 

3. Redis.client_list() 源代码

 1 def client_list(self, _type=None):
 2         """
 3         Returns a list of currently connected clients.
 4         If type of client specified, only that type will be returned.
 5         :param _type: optional. one of the client types (normal, master,
 6          replica, pubsub)
 7         """
 8         "Returns a list of currently connected clients"
 9         if _type is not None:
10             client_types = (normal, master, replica, pubsub)
11             if str(_type).lower() not in client_types:
12                 raise DataError("CLIENT LIST _type must be one of %r" % (
13                                 client_types,))
14             return self.execute_command(CLIENT LIST, bTYPE, _type)
15         return self.execute_command(CLIENT LIST)
1 info = redisclient.client_list()        # 获取client列表
1 output:
2 [
3 {id: 1319, addr: 127.0.0.1:48670, fd: 7, name: ‘‘, age: 5263, idle: 444, flags: N, db: 0, sub: 0, psub: 0, multi: -1, qbuf: 0, qbuf-free: 0, obl: 0, oll: 0, omem: 0, events: r, cmd: client}, 
4 {id: 1329, addr: 113.46.252.27:54863, fd: 8, name: ‘‘, age: 1, idle: 0, flags: N, db: 0, sub: 0, psub: 0, multi: -1, qbuf: 0, qbuf-free: 32768, obl: 0, oll: 0, omem: 0, events: r, cmd: client}
5 ]

 

4. Redis.config_ 配置参数相关源代码:

 1 def config_get(self, pattern="*"):
 2     "Return a dictionary of configuration based on the ``pattern``"
 3     return self.execute_command(CONFIG GET, pattern)
 4 
 5 def config_set(self, name, value):
 6     "Set config item ``name`` with ``value``"
 7     return self.execute_command(CONFIG SET, name, value)
 8 def config_rewrite(self):
 9     "Rewrite config file with the minimal change to reflect running config"
10     return self.execute_command(CONFIG REWRITE)

 

举例:内存扩容

1 info = redisclient.config_get(maxmemory)
2 info1 = redisclient.config_set(maxmemory,100MB)
3 info2 = redisclient.config_rewrite()
1 output:
2 info : {maxmemory: 104857600}
3 info1: True
4 info2: bOK

 

5. Redis.scan_iter() 源代码

 1 def scan_iter(self, match=None, count=None):
 2     """
 3     Make an iterator using the SCAN command so that the client doesnt
 4     need to remember the cursor position.
 5     ``match`` allows for filtering the keys by pattern
 6     ``count`` allows for hint the minimum number of returns
 7     """
 8     cursor = 0
 9     while cursor != 0:
10         cursor, data = self.scan(cursor=cursor, match=match, count=count)
11         for item in data:
12             yield item
1 redisclient.scan_iter(count=500):     # 每次扫描并返回500个key,

 

以上是Redis模块中常用的几个函数,能够有效提高工作效率!

 

  

以上是关于Python redis模块详解的主要内容,如果未能解决你的问题,请参考以下文章

Python中verbaim标签使用详解

pythonredis基本命令和基本用法详解

Redis学习之外部扩展模块详解

常用python日期日志获取内容循环的代码片段

Python模块导入详解

Redis学习之列表类型详解