sql >> Base de Datos >  >> NoSQL >> Redis

Forma correcta de usar Redis Connection Pool en Python

R1:Sí, utilizan el mismo conjunto de conexiones.

A2:Esta no es una buena práctica. Como no puede controlar la inicialización de esta instancia. Una alternativa podría ser usar 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)

Luego RedisClient será una clase singleton. No importa cuántas veces llame a client = RedisClient() , obtendrás el mismo objeto.

Entonces puedes usarlo como:

from RedisClient import RedisClient

client = RedisClient()
species = 'lion'
key = 'zoo:{0}'.format(species)
data = client.conn.hmget(key, 'age', 'weight')
print(data)

Y la primera vez que llame a client = RedisClient() realmente inicializará esta instancia.

O es posible que desee obtener una instancia diferente en función de diferentes argumentos:

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]