A1:Ja, de bruger den samme forbindelsespulje.
A2:Dette er ikke en god praksis. Da du ikke kan kontrollere initialiseringen af denne instans. Et alternativ kunne være at bruge 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)
Derefter RedisClient
vil være en singleton klasse. Ligegyldigt hvor mange gange du kalder client = RedisClient()
, får du det samme objekt.
Så du kan bruge det som:
from RedisClient import RedisClient
client = RedisClient()
species = 'lion'
key = 'zoo:{0}'.format(species)
data = client.conn.hmget(key, 'age', 'weight')
print(data)
Og første gang du kalder client = RedisClient()
vil faktisk initialisere denne instans.
Eller du ønsker måske at få en anden instans baseret på forskellige argumenter:
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]