简体   繁体   English

AWS Lambda 中的异步 HTTP 请求

[英]Asynchronous HTTP request in AWS Lambda

I am wanting to execute a http request inside of a lambda function, invoked by API Gateway.我想在 API 网关调用的 lambda 函数内执行 http 请求。 The problem is, the request takes a bit of time to complete (<20 seconds) and don't want the client waiting for a response.问题是,请求需要一些时间来完成(<20 秒)并且不希望客户端等待响应。 In my research on asynchronous requests, I learned that I can pass the X-Amz-Invocation-Type:Event header to make the request execute asynchronously, however this isn't working and the code still "waits" for the http request to complete.在我对异步请求的研究中,我了解到我可以通过X-Amz-Invocation-Type:Event标头使请求异步执行,但是这不起作用并且代码仍然“等待”http 请求完成.

Below is my lambda code:下面是我的 lambda 代码:

'use strict';

const https = require('https');

exports.handler = function (event, context, callback) {
    let requestUrl;
    requestUrl = event.queryStringParameters.url;

    https.get(requestUrl, (res) => {
        console.log('statusCode:', res.statusCode);
        console.log('headers:', res.headers);

        res.on('data', (d) => {
            process.stdout.write(d);
        });
    }).on('error', (e) => {
        console.error(e);
    });

    let response = {
        "statusCode": 200,
        "body": JSON.stringify(event.queryStringParameters)
    };
    callback(null, response);
};

Any help would be appreciated.任何帮助,将不胜感激。

You can use two Lambda functions. 您可以使用两个Lambda函数。

Lambda 1 is triggered by API Gateway then calls Lambda 2 asynchronously ( InvocationType = Event ) then returns a response to the user. Lambda 1由API网关触发,然后异步调用Lambda 2( InvocationType = Event ),然后向用户返回响应。

Lambda 2, once invoked, will trigger the HTTP request. Lambda 2一旦被调用,将触发HTTP请求。

Whatever you do, don't use two lambda functions.无论您做什么,都不要使用两个 lambda 函数。

You can't control how lambda is being called, async or sync.您无法控制 lambda 的调用方式,异步或同步。 The caller of the lambda decides that. lambda 的调用者决定了这一点。 For APIGW, it has decided to call lambda sync.对于 APIGW,它决定调用 lambda 同步。

The possible solutions are one of:可能的解决方案是以下之一:

  • SQS质量标准
  • Step Functions (SF)阶跃函数 (SF)
  • SNS社交网络

In your API, you call out to one of these services, get back a success, and then immediately return a 202 to your caller.在您的 API 中,您调用这些服务之一,获得成功,然后立即向您的调用者返回 202。

If you have a high volume of single or double action execution use SQS.如果您有大量的单操作或双操作执行,请使用 SQS。 If you have potentially long running with complex state logic use SF.如果您可能长时间运行复杂的状态逻辑,请使用 SF。 If you for someone reason want to ignore my suggestions, use SNS.如果您出于某种原因想忽略我的建议,请使用 SNS。

Each of these can (and should) call back out to a lambda.这些中的每一个都可以(并且应该)回调到 lambda。 In the case that you need to run more than 15 minutes, they can call back out to CodeBuild .如果您需要运行超过 15 分钟,他们可以回调CodeBuild Ignore the name of the service, it's just a lambda that supports up to 8 hour runs.忽略服务的名称,它只是一个支持长达 8 小时运行的 lambda。


Now, why not use two lambdas (L1, L2)?现在,为什么不使用两个 lambdas (L1, L2)? The answer is simple.答案很简单。 Once you respond that your async call was queued (SQS, SF, SNS), to your users (202).一旦您响应您的异步调用已排队(SQS、SF、SNS),您的用户 (202)。 They'll expect that it works 100%.他们会期望它 100% 有效。 But what happens if that L2 lambda fails.但是如果 L2 lambda 失败会发生什么。 It won't retry, it won't continue, and you may never know about it.它不会重试,也不会继续,你可能永远不会知道。

That L2 lambda's handler no longer exist, so you don't know the state any more. L2 lambda 的处理程序不再存在,因此您不再知道状态。 Further, you could try to add logging to L2 with wrapper try/catch but so many other types of failures could happen.此外,您可以尝试使用包装器try/catch将日志记录添加到 L2,但可能会发生许多其他类型的故障。 Even if you have that, is CloudWatch down, will you get the log?即使你有那个,CloudWatch 宕机了,你会得到日志吗? Possible not, it just isn't a reliable strategy.可能不是,它只是不是一个可靠的策略。 Sure if you are doing something you don't care about, you can build this arch, but this isn't how real production solutions are built.当然,如果你正在做一些你不关心的事情,你可以构建这个架构,但这不是真正的生产解决方案的构建方式。 You want a reliable process.你想要一个可靠的过程。 You want to trust that the baton was successfully passed to another service which take care of completing the user's transaction.您希望相信接力棒已成功传递给另一个负责完成用户交易的服务。 This is why you want to use one of the three services: SQS, SF, SNS.这就是为什么您要使用以下三种服务之一:SQS、SF、SNS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM