java - 异步 Lambda 代理集成

标签 java aws-lambda aws-api-gateway

我正在尝试从 AWS API Gateway 异步调用 AWS Lambda 函数。

我有一个长时间运行(2-3 分钟)的 Lambda 函数,我想从 HTTP Post 请求异步调用这个 Lambda 函数。我将 API 网关配置为 Lambda 代理集成(因为我想将未修改的主体传递给函数)这工作正常,但 30 秒后,由于 API 网关执行时间限制,我得到 504。

但是我无法调用异步函数。根据AWS docs如果我设置了haeder“X-Amz-Invocation-Type”应该是可能的,但这没有任何区别。

有人知道是否可以异步调用函数并使用代理集成?

最佳答案

AWS 表示如果您设置 X-Amz-Invocation-Type 是可能的标题到 Event ,但几个月前我遇到了同样的需求,这对我不起作用,所以我不确定情况是否仍然如此,或者是否只是我错误配置了它。也许你当时和我一样错过了同样的事情:我没有像文档建议的那样在集成请求中添加 InvocationType header ,所以这很可能是你的情况,但我仍然不能保证它有效)

documentation说:

Configure Lambda asynchronous invocation in the API Gateway console

In Integration Request, add an X-Amz-Invocation-Type header.

In Method Request, add an InvocationType header and map it to the X-Amz-Invocation-Type header in the Integration Request with either a static value of 'Event' or the header mapping expression of method.request.header.InvocationType. For the latter, the client must include the InvocationType:Event header when making a request to the API method.



如果这有效,那么您就可以开始了。

然而,我当时所做的是创建一个中间 Lambda,它实际上充当实际 Lambda 的代理。

有多种选项可以异步执行您的函数,但无论如何您都需要两个 Lambda 函数。

一种选择是通过 API Gateway 调用的函数异步调用另一个函数(它将实际执行您想要的任务)。
const params = {
        FunctionName: 'YOUR_FUNCTIONS_NAME',
        InvocationType: 'Event',
        Payload: JSON.parse(event.body) // this is the event coming from API Gateway
    };
    await lambda.invoke(params).promise(); // await here is only going to wait for the HTTP request to be successful. Once the 2nd Lambda is invoked, it will return immediately

另一种选择是将消息放入 SQS 并配置一个触发器,以便在 SQS 队列中有新消息时调用您的 Lambda。同样的事情也适用于 SNS 通知。

其他选项包括 Kinesis、DynamoDB Streams 等,但思路是一样的:通过 API Gateway 调用的函数必须是其他 Lambda 的代理。此代理将如何工作(向 SQS、SNS 发送消息,直接异步调用其他函数等)并不重要,重要的是绕过 API 网关 30 秒请求限制的概念。

关于java - 异步 Lambda 代理集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56055646/

相关文章:

python - 亚马逊 (AWS) API 网关 - 身份验证

java - log4j根据登录linux的人创建动态文件名

java - 您的项目位置包含空格。 (安卓工作室)

amazon-web-services - 客户端错误: An error occurred (403) when calling the HeadObject operation: Forbidden

performance - 使用内存不足的 Lambda 向 SQS 缓慢发送消息

mysql - 无服务器在本地工作,但在部署时不工作

amazon-web-services - Amazon API Gateway - 删除 API key

java - 在 MS Access 数据库中插入一行

java - 在Alluxio Web UI中,“服务器配置检查”已被警告

amazon-web-services - AWS API网关: When to create another API?