ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

Python redis模块详解

2019-11-24 21:01:49  阅读:247  来源: 互联网

标签:info Python Redis self redis client 详解 redisclient


在使用 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.106.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 doesn't 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', b'TYPE', _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: b'OK'

 

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 doesn't
 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模块中常用的几个函数,能够有效提高工作效率!

 

  

标签:info,Python,Redis,self,redis,client,详解,redisclient
来源: https://www.cnblogs.com/cuisi/p/11924234.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有