python中redis使用_Python中Redis连接池的正确使用方法

A1:是的,他们使用同一个连接池。在

A2:这不是一个好的做法。因为您无法控制此实例的初始化。另一种选择是使用singleton。在import redis

class Singleton(type):

"""

An metaclass for singleton purpose. Every singleton class should inherit from this class by 'metaclass=Singleton'.

"""

_instances = {}

def __call__(cls, *args, **kwargs):

if cls not in cls._instances:

cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)

return cls._instances[cls]

class RedisClient(object):

def __init__(self):

self.pool = redis.ConnectionPool(host = HOST, port = PORT, password = PASSWORD)

@property

def conn(self):

if not hasattr(self, '_conn'):

self.getConnection()

return self._conn

def getConnection(self):

self._conn = redis.Redis(connection_pool = self.pool)

那么RedisClient将是一个单例类。无论调用client = RedisClient()多少次,都会得到相同的对象。在

所以你可以像这样使用它:

^{pr2}$

第一次调用client = RedisClient()时,将实际初始化该实例。在

或者您可能希望基于不同的参数获取不同的实例:class Singleton(type):

"""

An metaclass for singleton purpose. Every singleton class should inherit from this class by 'metaclass=Singleton'.

"""

_instances = {}

def __call__(cls, *args, **kwargs):

key = (args, tuple(sorted(kwargs.items())))

if cls not in cls._instances:

cls._instances[cls] = {}

if key not in cls._instances[cls]:

cls._instances[cls][key] = super(Singleton, cls).__call__(*args, **kwargs)

return cls._instances[cls][key]