python-3.x 如何创建一个全球性的连接与Redis

vohkndzv  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(123)

我是新的python 3和python cio来自gevent和2.7。
如何创建一个全局连接,供所有Redis使用?例如,我将有一个进程,例如10个Redis线程,但我不希望每个线程都有一个单独的连接。为什么?.将有例如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连接

vql8enpb

vql8enpb1#

10个双头螺纹
以防万一-asyncio协程在一个线程中运行。并发性通过在I/O操作时在协程之间切换来实现。

为什么你的代码不工作?

asyncio_redis.Connection.create-是一个协程,你应该使用yield from等待这个操作来获取结果:

connection = yield from asyncio_redis.Connection.create(host='127.0.0.1', port=6379)

字符串

如何创建全局连接

如果你只有一个连接,你可能不会从使用Webcio中获得任何好处。并发请求可能需要可以使用的连接池。asyncio_redis有简单的方法来做到这一点,例如:

import asyncio
import asyncio_redis

@asyncio.coroutine
def main():
    connection = yield from asyncio_redis.Pool.create(host='127.0.0.1', port=6379, poolsize=10)
    try:
        # 3 requests running concurrently in single thread using connections from pool: 
        yield from asyncio.gather(
            connection.brpop(['queue:pixel'], timeout=0),
            connection.brpop(['queue:pixel'], timeout=0),
            connection.brpop(['queue:pixel'], timeout=0),
        )
    finally:
        connection.close()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()

Python 3.5+

如果你正在使用Python 3.5+,考虑使用更新的语法来定义和等待协程。

更新日期:

阻塞代码(例如,需要大量CPU时间的代码)不能直接在协程中使用:它会冻结你的事件循环,你将无法从阻塞代码中获得任何好处。
您可以使用run_in_executor在单独的进程中运行此代码,而不会阻塞事件循环:

from concurrent.futures import ProcessPoolExecutor

executor = ProcessPoolExecutor(max_workers=10)  # use number of cores here

async def worker():
    while True:
        data = await connection.brpop(['queue'], timeout=0)
        print(data)

        # await blocking_code from separate process:
        loop = asyncio.get_event_loop()
        result = await loop.run_in_executor(executor, blocking_code, data)

相关问题