python使用redispool的单例实现方式介绍

本文实例讲述了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使用redis pool的单例实现方式介绍相关文章请关注php中文网!

Posted in 未分类

发表评论