Python使用redis pool的一種單例實現(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相關內容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Anconda環(huán)境下Vscode安裝Python的方法詳解
anaconda指的是一個開源的Python發(fā)行版本,其包含了conda、Python等180多個科學包及其依賴項。這篇文章主要介紹了Anconda環(huán)境下Vscode安裝Python的方法,需要的朋友可以參考下2020-03-03Python 數(shù)據(jù)科學 Matplotlib圖庫詳解
Matplotlib 是 Python 的二維繪圖庫,用于生成符合出版質量或跨平臺交互環(huán)境的各類圖形。今天通過本文給大家分享Python 數(shù)據(jù)科學 Matplotlib的相關知識,感興趣的朋友一起看看吧2021-07-07python使用for循環(huán)計算0-100的整數(shù)的和方法
今天小編就為大家分享一篇python使用for循環(huán)計算0-100的整數(shù)的和方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02python基于paramiko將文件上傳到服務器代碼實現(xiàn)
這篇文章主要介紹了python基于paramiko將文件上傳到服務器代碼實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-07-07