6

foo.py2 つの異なるモジュールとbar.pyRedis 接続プールから接続を取得するにはどうすればよいですか? つまり、アプリをどのように構成すればよいのでしょうか。

目標は、すべてのモジュールが接続を取得するための単一の接続プールを持つことだと思います。

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)

bar.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)

bar.py

from RedisClient import redisClient

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

1 に答える 1