在Python中创建和管理多个Redis连接

10 投票
1 回答
14458 浏览
提问于 2025-04-17 10:57

我正在使用Redis来存储两个数据库:0和1,使用的是Redis-py这个客户端库。我想为每个数据库创建两个连接。目前,我是这样做的:

>>> connection0 = redis.Connection(host = 'localhost', port = 6379, db = 0)
>>> connection1 = redis.Connection(host = 'localhost', port = 6379, db = 1)
>>> connection0.connect()

不过,我似乎找不到从连接中创建Redis对象的方法。

>>> store0 = redis.Redis(connection0)
>>> store0.info()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/site-packages/redis-2.4.11-py2.7.egg/redis/client.py", line 341, in info
    return self.execute_command('INFO')
  File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/site-packages/redis-2.4.11-py2.7.egg/redis/client.py", line 278, in execute_command
    connection.send_command(*args)
  File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/site-packages/redis-2.4.11-py2.7.egg/redis/connection.py", line 258, in send_command
    self.send_packed_command(self.pack_command(*args))
  File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/site-packages/redis-2.4.11-py2.7.egg/redis/connection.py", line 241, in send_packed_command
    self.connect()
  File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/site-packages/redis-2.4.11-py2.7.egg/redis/connection.py", line 187, in connect
    sock = self._connect()
  File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/site-packages/redis-2.4.11-py2.7.egg/redis/connection.py", line 198, in _connect
    sock.connect((self.host, self.port))
  File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
TypeError: coercing to Unicode: need string or buffer, Connection found

我是不是犯了初学者的错误?

1 个回答

15

你真的不应该这样创建连接。让我引用一下redis-py的文档。

在后台,redis-py使用一个连接池来管理与Redis服务器的连接。默认情况下,你创建的每个Redis实例都会创建自己的连接池。你可以通过将已经创建的连接池实例传递给Redis类的connection_pool参数来覆盖这个行为,使用一个现有的连接池。你可能会选择这样做,以便实现客户端分片,或者更细致地控制连接的管理方式。

>>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
>>> r = redis.StrictRedis(connection_pool=pool)

你不能指定一个单独的连接来与这个库一起使用。每个Redis实例都会有自己的连接池。当调用execute_command()时,它会从连接池中取出一个连接(或者打开一个新的连接)来使用。如果你只想让你的客户端一次最多有一个连接,可以将max_connections设置为1。

撰写回答