Python 更新异步支持的互操作性
久违的 iop 更新文章!
自 iop 命令行界面发布以来,有哪些令人兴奋的新功能呢?主要有两大亮点:
品牌焕新详解
为契合项目发展,原 grongier.pex 模块已更名为 iop。 为了兼容旧版本,grongier.pex 模块暂时保留,但未来将被移除,请及时迁移至 iop。
立即学习“Python免费学习笔记(深入)”;
异步操作支持详解
iop 早期版本支持异步调用,但无法直接使用异步函数和协程。 在介绍新功能前,先简述 InterSystems IRIS 中异步调用的机制,并通过两个示例演示 iop 如何使用异步调用。
旧版异步调用回顾
以下代码展示了旧版异步调用的工作方式:
from iop import businessprocessfrom msg import mymessageclass mybp(businessprocess): def on_message(self, request): msg_one = mymessage(message="message1") msg_two = mymessage(message="message2") self.send_request_async("python.mybo", msg_one,completion_key="1") self.send_request_async("python.mybo", msg_two,completion_key="2") def on_response(self, request, response, call_request, call_response, completion_key): if completion_key == "1": self.response_one = call_response elif completion_key == "2": self.response_two = call_response def on_complete(self, request, response): self.log_info(f"received response one: {self.response_one.message}") self.log_info(f"received response two: {self.response_two.message}")
其工作原理与 IRIS 中的异步调用类似:send_request_async 方法发送请求,收到响应后调用 on_response 方法。 completion_key 参数用于区分不同的响应。
多同步请求发送
虽然并非全新功能,但值得一提的是,现在可以并行发送多个同步请求:
from iop import businessprocessfrom msg import mymessageclass mymultibp(businessprocess): def on_message(self, request): msg_one = mymessage(message="message1") msg_two = mymessage(message="message2") tuple_responses = self.send_multi_request_sync([("python.mymultibo", msg_one), ("python.mymultibo", msg_two)]) self.log_info("all requests have been processed") for target,request,response,status in tuple_responses: self.log_info(f"received response: {response.message}")
此例中,我们并行向同一个业务操作发送两个请求,响应结果为一个元组,包含每个调用的目标、请求、响应和状态。 此方法适用于无需关注响应顺序的多个请求场景。
异步函数和协程
iop 如何使用异步函数和协程?请看示例:
import asynciofrom iop import BusinessProcessfrom msg import MyMessageclass MyAsyncNGBP(BusinessProcess): def on_message(self, request): results = asyncio.run(self.await_response(request)) for result in results: print(f"Received response: {result.message}") async def await_response(self, request): msg_one = MyMessage(message="Message1") msg_two = MyMessage(message="Message2") # use asyncio.gather to send multiple requests asynchronously # using the send_request_async_ng method tasks = [self.send_request_async_ng("Python.MyAsyncNGBO", msg_one), self.send_request_async_ng("Python.MyAsyncNGBO", msg_two)] return await asyncio.gather(*tasks)
此例使用 send_request_async_ng 方法并行发送多个请求。await_response 方法是一个协程,发送请求并等待所有响应。asyncio.gather 函数确保所有响应被并行接收。
使用异步函数和协程的优势:
send_request_async、send_multi_request_sync 和 send_request_async_ng 的区别
总结
选择合适的异步调用方法取决于具体需求。 祝您多线程编程愉快! 如果您读到这里,请在评论区留下“boomerang”,这对我意义重大!感谢您的阅读!