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

yipeiwu_com6年前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使用pil库实现图片合成实例代码

python使用pil库实现图片合成实例代码

本文研究的主要是python PIL实现图片合成的相关内容,具体介绍如下,分享实例代码。 在项目中需要将两张图片合在一起。遇到两种情况,一种就是两张非透明图片的合成, 一种是涉及到透明p...

举例讲解Python中字典的合并值相加与异或对比

字典合并值相加 在统计汇总游戏数据的时候,有些数据是是每天用字典存的,当我要对多天汇总的时候,就需要合并字典了。 如果key相同的话它们的值就相加。 不能用update方法,因为用upd...

pygame实现俄罗斯方块游戏(基础篇1)

pygame实现俄罗斯方块游戏(基础篇1)

本文实例为大家分享了pygame实现俄罗斯方块游戏的具体代码,基础的第一篇,供大家参考,具体内容如下 一、初始界面 之前的游戏都比较简单,所以代码都是面向过程的写法,这次游戏后面可能会写...

ubuntu 18.04搭建python环境(pycharm+anaconda)

ubuntu 18.04搭建python环境(pycharm+anaconda)

ubuntu 系统自带的 python 有多个版本,使用时难免会遇到环境变量出错,特别是当自动化运行脚本的时候。特别是近一个月来,实验室的小伙伴们的都倾心于 python。为了帮助小伙伴...

python中pandas.DataFrame的简单操作方法(创建、索引、增添与删除)

前言 最近在网上搜了许多关于pandas.DataFrame的操作说明,都是一些基础的操作,但是这些操作组合起来还是比较费时间去正确操作DataFrame,花了我挺长时间去调整BUG的。...