Dex*_*ter 8 python connection-pooling redis
我使用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()
Run Code Online (Sandbox Code Playgroud)
但是,我似乎没有找到从连接创建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
Run Code Online (Sandbox Code Playgroud)
我在这里犯了一个菜鸟错误吗?
Sim*_*ann 12
你真的不应该创建这样的连接.让我引用redis-py文档.
在幕后,redis-py使用连接池来管理与Redis服务器的连接.默认情况下,您创建的每个Redis实例将依次创建自己的连接池.您可以通过将已创建的连接池实例传递给Redis类的connection_pool参数来覆盖此行为并使用现有连接池.您可以选择执行此操作以实现客户端分片,或者对如何管理连接进行更精细的控制.
>>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
>>> r = redis.StrictRedis(connection_pool=pool)
Run Code Online (Sandbox Code Playgroud)
您无法指定要与库一起使用的单个连接.每个Redis实例都有自己的连接池.调用execute_command()时,它将从池中弹出连接(或打开一个新连接)并使用该连接.如果您只希望客户端一次最多连接一个,请将max_connections设置为1.
| 归档时间: |
|
| 查看次数: |
7790 次 |
| 最近记录: |