国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python與Redis的連接教程

2020-02-23 00:49:19
字體:
來源:轉載
供稿:網友

今天在寫zabbix storm job監控腳本的時候用到了python的redis模塊,之前也有用過,但是沒有過多的了解,今天看了下相關的api和源碼,看到有ConnectionPool的實現,這里簡單說下。
在ConnectionPool之前,如果需要連接redis,我都是用StrictRedis這個類,在源碼中可以看到這個類的具體解釋:
 
redis.StrictRedis Implementation of the Redis protocol.This abstract class provides a Python interface to all Redis commands and an
implementation of the Redis protocol.Connection and Pipeline derive from this, implementing how the commands are sent and received to the Redis server

使用的方法:
 

 r=redis.StrictRedis(host=xxxx, port=xxxx, db=xxxx) r.xxxx()

有了ConnectionPool這個類之后,可以使用如下方法
 

pool = redis.ConnectionPool(host=xxx, port=xxx, db=xxxx)r = redis.Redis(connection_pool=pool)

這里Redis是StrictRedis的子類
簡單分析如下:
在StrictRedis類的__init__方法中,可以初始化connection_pool這個參數,其對應的是一個ConnectionPool的對象:
 

class StrictRedis(object):........  def __init__(self, host='localhost', port=6379,         db=0, password=None, socket_timeout=None,         socket_connect_timeout=None,         socket_keepalive=None, socket_keepalive_options=None,         connection_pool=None, unix_socket_path=None,         encoding='utf-8', encoding_errors='strict',         charset=None, errors=None,         decode_responses=False, retry_on_timeout=False,         ssl=False, ssl_keyfile=None, ssl_certfile=None,         ssl_cert_reqs=None, ssl_ca_certs=None):     if not connection_pool:       ..........       connection_pool = ConnectionPool(**kwargs)     self.connection_pool = connection_pool

在StrictRedis的實例執行具體的命令時會調用execute_command方法,這里可以看到具體實現是從連接池中獲取一個具體的連接,然后執行命令,完成后釋放連接:

 

  # COMMAND EXECUTION AND PROTOCOL PARSING  def execute_command(self, *args, **options):    "Execute a command and return a parsed response"    pool = self.connection_pool    command_name = args[0]    connection = pool.get_connection(command_name, **options) #調用ConnectionPool.get_connection方法獲取一個連接    try:      connection.send_command(*args) #命令執行,這里為Connection.send_command      return self.parse_response(connection, command_name, **options)    except (ConnectionError, TimeoutError) as e:      connection.disconnect()      if not connection.retry_on_timeout and isinstance(e, TimeoutError):        raise      connection.send_command(*args)       return self.parse_response(connection, command_name, **options)    finally:      pool.release(connection) #調用ConnectionPool.release釋放連接            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 彩票| 安图县| 河曲县| 巢湖市| 融水| 斗六市| 保亭| 巴彦淖尔市| 饶河县| 上思县| 翼城县| 定远县| 宁明县| 富源县| 拉孜县| 台中县| 婺源县| 台安县| 小金县| 堆龙德庆县| 甘肃省| 翁源县| 扎鲁特旗| 宝坻区| 梁山县| 宁陕县| 襄汾县| 天镇县| 连州市| 达孜县| 临漳县| 英吉沙县| 松原市| 温宿县| 永仁县| 长乐市| 拜城县| 富蕴县| 望都县| 蒙城县| 密山市|