首页 文章

如何通过API网关使用事件调用类型调用Lambda函数?

提问于
浏览
5

文件说:

默认情况下,Invoke API采用RequestResponse调用类型 . 您可以选择通过将Event指定为InvocationType来请求异步执行 .

所以我可以发送到我的函数(python)是InvocationType:事件无处不在:

curl -X POST "https://X.execute-api.us-east-1.amazonaws.com/prod/Y?InvocationType=Event" 
-d "InvocationType:Event" 
-H "X-Amz-Invocation-Type:Event"

(function sleeps 3 seconds then responses)

null

但不是Async ......文档也说:

当您通过AWS控制台或使用Amazon API Gateway通过HTTPS调用Lambda函数时,Lambda始终使用RequestResponse调用类型 .

我知道可以通过aws-CLI实现,如果可以从API网关 endpoints 进行,我不明白 .

3 回答

  • 0

    创建两个Lambda,并在第一个使用Lambda.Client.invoke时使用InvocationType = Event处理Lambda的专用ApiGateway请求 . 第二个执行您希望ApiGateway请求异步调用的逻辑 .

    专用ApiGateway Lambda处理程序示例:

    from __future__ import print_function
    
    import boto3
    import json
    
    def lambda_handler(event, context):
        response = client.invoke(
            FunctionName='<your_long_task_running_function_executer>',
            InvocationType='Event',
            Payload=json.dumps(event)
        )
        return { "result": "OK" }
    

    您可能希望检测到发送请求的失败以及该类别的其他条件,但由于我主要不使用python,因此我将把这个逻辑留给您 .

    附:请注意,invoke_async已弃用
    p.p.s.抱歉,我的帐户是新的,我没有't have the rep to add these as a comment: 0. I borrowed from what you answered; 1. you are using a deprecated api; and 2. you ought (clearly it'很好)将 InvocationType = 'Event' 添加到您的通话中 .

  • 2

    我意识到API网关只能通过设计调用RequestResponse的lambda函数 .

    但你可以写2个函数:

    • “函数接收器”,用于调用“函数 Actuator ”的异步调用
    from __future__ import print_function
    
    import boto3
    import json
    
    def lambda_handler(event, context):
        client = boto3.client('lambda')
        client.invoke_async(
            FunctionName='my_long_task_running_function_executer',
            InvokeArgs=json.dumps(event)
        )
        return {"result": "OK"}
    
    • A "Function Executer"执行长时间运行的任务 .

    然后,您将拥有一个可以从API网关开始并将其作为InvocationType = Event执行的进程 .

  • 10

    根据这篇文章你可以传递一个 Headers :X-Amz-Invocation-Type:Event https://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-lambda.html

相关问题