python中redis使用_Python中Redis连接池的正确使用方法

A1:是的,他们使用同一个连接池。在

A2:这不是一个好的做法。因为您无法控制此实例的初始化。另一种选择是使用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)

那么RedisClient将是一个单例类。无论调用client = RedisClient()多少次,都会得到相同的对象。在

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

^{pr2}$

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值