Python使用redis pool的一种单例实现方式

yipeiwu_com5年前Python基础

本文实例讲述了Python使用redis pool的一种单例实现方式。分享给大家供大家参考,具体如下:

为适应多个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相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python将字母转化为数字实例方法

python将字母转化为数字实例方法

python如何将字母转化为数字? 将英文字母转成数字: 转换 ord('F') 反转 chr(70) python ord() 函数 是 chr() 函数(...

python实现随机梯度下降法

python实现随机梯度下降法

看这篇文章前强烈建议你看看上一篇python实现梯度下降法: 一、为什么要提出随机梯度下降算法 注意看梯度下降法权值的更新方式(推导过程在上一篇文章中有)  也就是说每次更新...

Pycharm编辑器技巧之自动导入模块详解

Pycharm编辑器技巧之自动导入模块详解

前言 pycharm可以很方便的管理Python的解释器(如果安装了多个的话),以及第三方模块,包。Pycharm是很多Python开发者的首选IDE,如果能把一个工具熟练运用,往往有事...

python 查找字符串是否存在实例详解

python中查找指定的字符串的方法如下: code #查询 def selStr(): sStr1 = 'jsjtt.com' sStr2 = 'com' #inde...

Ubuntu 下 vim 搭建python 环境 配置

1. 安装完整的vim # apt-get install vim-gnome 2. 安装ctags,ctags用于支持taglist,必需! # apt-get instal...