Python使用redis pool的一種單例實現(xiàn)方式
更新時間:2016年04月16日 09:05:46 作者:mo_guang
這篇文章主要介紹了Python使用redis pool的一種單例實現(xiàn)方式,結(jié)合實例形式分析了Python操作redis模塊實現(xiàn)共享同一個連接池的相關技巧,需要的朋友可以參考下
本文實例講述了Python使用redis pool的一種單例實現(xiàn)方式。分享給大家供大家參考,具體如下:
為適應多個redis實例共享同一個連接池的場景,可以類似于以下單例方式實現(xiàn):
import redis
class RedisDBConfig:
HOST = '127.0.0.1'
PORT = 6379
DBID = 0
def operator_status(func):
'''''get operatoration status
'''
def gen_status(*args, **kwargs):
error, result = None, None
try:
result = func(*args, **kwargs)
except Exception as e:
error = str(e)
return {'result': result, 'error': error}
return gen_status
class RedisCache(object):
def __init__(self):
if not hasattr(RedisCache, 'pool'):
RedisCache.create_pool()
self._connection = redis.Redis(connection_pool = RedisCache.pool)
@staticmethod
def create_pool():
RedisCache.pool = redis.ConnectionPool(
host = RedisDBConfig.HOST,
port = RedisDBConfig.PORT,
db = RedisDBConfig.DBID)
@operator_status
def set_data(self, key, value):
'''''set data with (key, value)
'''
return self._connection.set(key, value)
@operator_status
def get_data(self, key):
'''''get data by key
'''
return self._connection.get(key)
@operator_status
def del_data(self, key):
'''''delete cache by key
'''
return self._connection.delete(key)
if __name__ == '__main__':
print RedisCache().set_data('Testkey', "Simple Test")
print RedisCache().get_data('Testkey')
print RedisCache().del_data('Testkey')
print RedisCache().get_data('Testkey')
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python 中 AttributeError: ‘NoneType‘ obje
Python “AttributeError: ‘NoneType’ object has no attribute” 發(fā)生在我們嘗試訪問 None 值的屬性時,例如 來自不返回任何內(nèi)容的函數(shù)的賦值, 要解決該錯誤,請在訪問屬性之前更正分配,本文通過示例給大家說明錯誤是如何發(fā)生的,感興趣的朋友一起看看吧2023-08-08
matplotlib jupyter notebook 圖像可視化 plt show操作
這篇文章主要介紹了matplotlib jupyter notebook 圖像可視化 plt show操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
在Python的Django框架中用流響應生成CSV文件的教程
這篇文章主要介紹了在Python的Django框架中用流響應生成CSV文件的教程,作者特別講到了防止CSV文件中的中文避免出現(xiàn)亂碼等問題,需要的朋友可以參考下2015-05-05

