6

两个不同的模块应该如何foo.pybar.py一个 Redis 连接池中获取连接?换句话说,我们应该如何构建应用程序?

我相信目标是为所有模块提供一个连接池,以便从中获取连接。

Q1:在我的示例中,两个模块是否从同一个连接池中获得连接?

Q2:是否可以在 中创建 RedisClient 实例RedisClient.py,然后将该实例导入到其他 2 个模块中?或者,还有更好的方法?

Q3:conn实例变量的延迟加载真的有用吗?

RedisClient.py

import redis

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 = RedisClient()

foo.py

from RedisClient import redisClient

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

酒吧.py

from RedisClient import redisClient

print(redisClient.conn.ping())

还是这样更好?

RedisClient.py

import redis

class RedisClient(object):

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

    def getConnection(self):
        return redis.Redis(connection_pool = self.pool)

redisClient = RedisClient()

foo.py

from RedisClient import redisClient

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

酒吧.py

from RedisClient import redisClient

print(redisClient.getConnection().ping())
4

1 回答 1

7

A1: Yes, they use the same connection pool.

A2: This isn't a good practice. As you cannot control the initialization of this instance. An alternative could be use 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)

Then RedisClient will be a singleton class. Not matter how many times you call client = RedisClient(), you will get the same object.

So you can use it like:

from RedisClient import RedisClient

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

And the first time you call client = RedisClient() will actually initialize this instance.

Or you may want to get different instance based on different arguments:

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]
于 2018-03-21T05:34:24.370 回答