【问题标题】:Is it a good idea to use create_future asyncio?使用 create_future asyncio 是个好主意吗?
【发布时间】:2021-04-13 08:40:07
【问题描述】:

文档说: 通常不需要在应用程序级代码中创建 Future 对象。 但是我们经常可以看到如下代码(简单的RPCrabbitmq客户端):

import asyncio
import uuid
from aio_pika import connect, IncomingMessage, Message


class FibonacciRpcClient:
    def __init__(self, loop):
        self.connection = None
        self.channel = None
        self.callback_queue = None
        self.futures = {}
        self.loop = loop

    async def connect(self):
        self.connection = await connect(
            "amqp://guest:guest@localhost/", loop=loop
        )
        self.channel = await self.connection.channel()
        self.callback_queue = await self.channel.declare_queue(exclusive=True)
        await self.callback_queue.consume(self.on_response)

        return self

    def on_response(self, message: IncomingMessage):
        future = self.futures.pop(message.correlation_id)
        future.set_result(message.body)

    async def call(self, n):
        correlation_id = str(uuid.uuid4())
        future = self.loop.create_future()

        self.futures[correlation_id] = future

        await self.channel.default_exchange.publish(
            Message(
                str(n).encode(),
                content_type="text/plain",
                correlation_id=correlation_id,
                reply_to=self.callback_queue.name,
            ),
            routing_key="rpc_queue",
        )

        return int(await future)


async def main(loop):
    fibonacci_rpc = await FibonacciRpcClient(loop).connect()
    print(" [x] Requesting fib(30)")
    response = await fibonacci_rpc.call(30)
    print(" [.] Got %r" % response)


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

在上述情况下使用 loop.create_future() 是个好主意吗?使用它是最佳做法吗?

【问题讨论】:

    标签: python rabbitmq python-asyncio


    【解决方案1】:

    一般情况下,无需致电create_future。 docs 建议将此函数保留在任何面向用户的 API 之外。

    但在您分享的示例中,该方法用于通过所有其他方式正确获取同步的结果 on_response 操作。

    当需要将同步接口与async/await结合起来时,可以/应该在其他库上编写异步包装器时使用Futures。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-09
      • 2010-11-05
      • 2012-04-27
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      相关资源
      最近更新 更多