【发布时间】:2017-08-11 00:17:40
【问题描述】:
我是来自 gevent 和 2.7 的 python 3 和 asyncio 的新手 ....
如何创建一个可供所有人用于 reids 的全局连接?例如。我将有 1 个进程,例如10 个异步线程,但我不希望每个线程有单独的连接。为什么?...会有例如100 个核心,每个核心 10 个线程,并且不希望有那么多连接到 redis
import asyncio
import asyncio_redis
async def worker():
while True:
data = await connection.brpop(['queue'], timeout=0)
print(data)
res = blocking_code(data)
await connection.set('test',res)
#Process raw data here and all code is blocking
def blocking_code(data):
results = {}
return results
if __name__ == '__main__':
connection = asyncio_redis.Connection.create(host='127.0.0.1', port=6379, poolsize=2)
loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(worker()), asyncio.ensure_future(worker())]
loop.run_until_complete(asyncio.gather(*tasks))
connection.close()
Traceback (most recent call last):
File "/Users//worker.py", line 14, in <module>
loop.run_until_complete(example())
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 466, in run_until_complete
return future.result()
File "/Users//worker.py", line 7, in example
data = yield from connection.brpop(['queue'], timeout=0)
AttributeError: 'generator' object has no attribute 'brpop'
所以在上面我有两个任务,但我只想要 1 个 redis 连接
【问题讨论】: