【python】使用redis pool的一种单例实现方式
2014-05-26 15:28
579 查看
为适应多个redis实例共享同一个连接池的场景,可以类似于以下单例方式实现:
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使用redis pool的一种单例实现方式
- Python使用redis pool的一种单例实现方式
- Python:使用threading模块实现多线程编程二[两种方式起线程]
- Python使用面向对象方式创建线程实现12306售票系统
- 一种分析代金券使用分布情况的方法python实现版(上)
- Python多线程 - 使用threading模块实现多线程的 3 种方式
- 详解python使用递归、尾递归、循环三种方式实现斐波那契数列
- 一种分析代金券使用分布情况的方法python实现版(下)
- iOS监听耳机插拔的不使用系统通知实现的一种方式
- Python:使用threading模块实现多线程编程二[两种方式起线程]
- 循环赛问题 日程安排的一种排列方式 使用C++实现
- 使用Python以优雅的方式实现根据shp数据对栅格影像进行切割
- 使用JavaScript实现访问本站点任何页面都加载Frame的一种实现方式
- 使用 Python 实现文件递归遍历的三种方式
- 使用一种独特的方式实现动画框架
- Python使用面向对象方式创建线程实现12306售票系统
- Python:使用threading模块实现多线程编程二[两种方式起线程]
- python 元类型编程, 单例模式SingleTon的一种实现方式
- 使用 Python 实现文件递归遍历的 3 种方式
- 关于Python中一种回调方式的实现