[英]AWS Lambda c# asynchronous API calls
I have a AWS lambda function written in c#. 我有一个用c#编写的AWS lambda函数。 This function is responsible for calling 5-6 API calls (Post requests). 该函数负责调用5-6个API调用(Post请求)。
Question: I want my lambda function to execute and respond within a second. 问题:我希望我的lambda函数能够在一秒钟内执行并响应。 How can I asynchronously make my API calls such that lambda function can finish all of these within my time limit without waiting for the responses from the API calls? 我如何异步地进行API调用,以便lambda函数可以在我的时间限制内完成所有这些,而无需等待API调用的响应? Ideally, I want to implement a fire and forget API call system that sends the final response back without any delay. 理想情况下,我想实现一个火灾并忘记API调用系统,该系统可以毫无延迟地发送最终响应。
According to AWS lambda documentation , I have to use await operator with asynchronous calls in lambda to avoid the function being completed before the asynchronous calls are finished. 根据AWS lambda 文档 ,我必须在lambda中使用await运算符和异步调用,以避免在异步调用完成之前完成该函数。
Am I missing something here? 我在这里错过了什么吗? Or is there a way to accomplish this? 或者有办法实现这一目标吗?
Thanks 谢谢
You can't run code "outside" of a serverless request. 您无法在无服务器请求的“外部”运行代码。 To try to do so will only bring pain - since your serverless host has no idea that your code is incomplete, it will feel free to terminate your hosting process. 尝试这样做只会带来痛苦 - 因为您的无服务器主机不知道您的代码是不完整的,它可以随时终止您的托管过程。
The proper solution is to have two lambdas separated by a queue. 正确的解决方案是让两个 lambda由队列分隔。 The first (externally-facing) lambda takes the POST request, drops a message on the queue, and returns its response to the caller. 第一个(面向外部的)lambda接受POST请求,在队列上删除消息,并将其响应返回给调用者。
The second (internal-only) lambda monitors the queue and does the API calls. 第二个(仅限内部的)lambda监视队列并执行API调用。
For your use case, using AWS Step functions will provide a fully managed solution. 对于您的使用案例,使用AWS Step功能将提供完全托管的解决方案。 The steps are as follows. 步骤如下。
There are few benefits with Step functions over custom Lambda flow implementation. 与自定义Lambda流实现相比,Step功能几乎没有什么好处。
If you just want a fire and forget, then don't use await. 如果你只是想要一场大火而忘记,那么就不要使用等待。 Just use an HttpClient method (get, put, etc.) to call the API, and you're done. 只需使用HttpClient方法(get,put等)来调用API,就完成了。 Those methods return a Task<HttpResponseMessage>
which you don't care about, so it's fine for your Lambda to exit at that point. 这些方法返回一个你不关心的Task<HttpResponseMessage>
,所以你的Lambda可以在那时退出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.