gpt4 book ai didi

python - Python中Redis连接池的正确使用方式

转载 作者:IT王子 更新时间:2023-10-29 06:05:02 32 4
gpt4 key购买 nike

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

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

问题 1:在我的示例中,两个模块是否从同一连接池获取连接?

问题 2: 是否可以在 RedisClient.py 中创建 RedisClient 实例,然后将该实例导入到其他 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())

最佳答案

A1:是的,他们使用相同的连接池。

A2:这不是一个好的做法。因为您无法控制此实例的初始化。另一种方法是使用单例。

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(metaclass=Singleton):

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(),您都将获得相同的对象。

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

from RedisClient import RedisClient

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

而您第一次调用 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]

关于python - Python中Redis连接池的正确使用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49398590/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com