Python使用redis pool的一種單例實(shí)現(xiàn)方式
本文實(shí)例講述了Python使用redis pool的一種單例實(shí)現(xiàn)方式。分享給大家供大家參考,具體如下:
為適應(yīng)多個(gè)redis實(shí)例共享同一個(gè)連接池的場(chǎng)景,可以類似于以下單例方式實(shí)現(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')
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Anconda環(huán)境下Vscode安裝Python的方法詳解
anaconda指的是一個(gè)開源的Python發(fā)行版本,其包含了conda、Python等180多個(gè)科學(xué)包及其依賴項(xiàng)。這篇文章主要介紹了Anconda環(huán)境下Vscode安裝Python的方法,需要的朋友可以參考下2020-03-03基于Python的XSS測(cè)試工具XSStrike使用方法
XSS(Cross Site Scripting,跨站腳本攻擊)是一類特殊的Web客戶端腳本注入攻擊手段,通常指攻擊者通過“HTML注入”篡改了網(wǎng)頁(yè),插入惡意的腳本,從而在用戶瀏覽網(wǎng)頁(yè)時(shí)控制瀏覽器的一種攻擊。2017-07-07Python 數(shù)據(jù)科學(xué) Matplotlib圖庫(kù)詳解
Matplotlib 是 Python 的二維繪圖庫(kù),用于生成符合出版質(zhì)量或跨平臺(tái)交互環(huán)境的各類圖形。今天通過本文給大家分享Python 數(shù)據(jù)科學(xué) Matplotlib的相關(guān)知識(shí),感興趣的朋友一起看看吧2021-07-07總結(jié)Python連接CS2000的詳細(xì)步驟
今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識(shí),文章圍繞著Python連接CS2000的詳細(xì)步驟展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06python使用for循環(huán)計(jì)算0-100的整數(shù)的和方法
今天小編就為大家分享一篇python使用for循環(huán)計(jì)算0-100的整數(shù)的和方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-02-02python基于paramiko將文件上傳到服務(wù)器代碼實(shí)現(xiàn)
這篇文章主要介紹了python基于paramiko將文件上傳到服務(wù)器代碼實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07