作为生产者的异步套接字服务器,有工作人员在使用它

问题描述 投票:0回答:1

[我开始使用asyncio模块,我想知道是否有可能构建一个tcp服务器,该服务器将一些工作放在队列中以便某些工作人员执行它。

我尝试合并python文档中示例的代码。

import asyncio

async def handle_echo(reader, writer):
    data = await reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')

    print(f"Received {message!r} from {addr!r}")

    print(f"Send: {message!r}")
    writer.write(data)
    await writer.drain()

    print("Close the connection")
    writer.close()

async def main():
    server = await asyncio.start_server(
        handle_echo, '127.0.0.1', 8888)

    addr = server.sockets[0].getsockname()
    print(f'Serving on {addr}')

    async with server:
        await server.serve_forever()

asyncio.run(main())

和工人

import asyncio
import random
import time


async def worker(name, queue):
    while True:
        # Get a "work item" out of the queue.
        sleep_for = await queue.get()

        # Sleep for the "sleep_for" seconds.
        await asyncio.sleep(sleep_for)

        # Notify the queue that the "work item" has been processed.
        queue.task_done()

        print(f'{name} has slept for {sleep_for:.2f} seconds')


async def main():
    # Create a queue that we will use to store our "workload".
    queue = asyncio.Queue()

    # Generate random timings and put them into the queue.
    total_sleep_time = 0
    for _ in range(20):
        sleep_for = random.uniform(0.05, 1.0)
        total_sleep_time += sleep_for
        queue.put_nowait(sleep_for)

    # Create three worker tasks to process the queue concurrently.
    tasks = []
    for i in range(3):
        task = asyncio.create_task(worker(f'worker-{i}', queue))
        tasks.append(task)

    # Wait until the queue is fully processed.
    started_at = time.monotonic()
    await queue.join()
    total_slept_for = time.monotonic() - started_at

    # Cancel our worker tasks.
    for task in tasks:
        task.cancel()
    # Wait until all worker tasks are cancelled.
    await asyncio.gather(*tasks, return_exceptions=True)

    print('====')
    print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')
    print(f'total expected sleep time: {total_sleep_time:.2f} seconds')


asyncio.run(main())

[我一开始编写代码,就会想到很多问题。

服务器是否创建自己的事件循环?

当工作人员从服务器填充的队列中消耗作业时,我可以为服务器提供服务吗?>>

是否有针对此类应用程序的良好指南,或用于指导人们使用异步带来的新术语呢?

我开始使用asyncio模块,我想知道是否有可能构建一个tcp服务器,该服务器将一些工作放入队列中,以便某些工作人员执行它。我尝试合并代码...

python sockets tcp python-asyncio asyncsocket
1个回答
0
投票

我不确定,但是问题出在创建自己的事件循环的队列上,所以我不得不在主要的异步函数中创建它。start_servingserve_forever没有任何区别。我仍在尝试和研究文档,因此暂时将接受此答案。

© www.soinside.com 2019 - 2024. All rights reserved.