node.js AWS Lambda 函数可以调用另一个函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31714788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:10:58  来源:igfitidea点击:

Can an AWS Lambda function call another

node.jsamazon-web-servicesaws-lambdaaws-api-gateway

提问by Silver

I have 2 Lambda functions - one that produces a quote and one that turns a quote into an order. I'd like the Order lambda function to call the Quote function to regenerate the quote, rather than just receive it from an untrusted client.

我有 2 个 Lambda 函数 - 一个生成报价,一个将报价转换为订单。我希望 Order lambda 函数调用 Quote 函数来重新生成报价,而不是仅仅从不受信任的客户端接收报价。

I've looked everywhere I can think of - but can't see how I'd go about chaining or calling the functions...surely this exists!

我找遍了我能想到的所有地方 - 但看不出我将如何链接或调用函数......这肯定存在!

回答by Nicolas Grenié

I found a way using the aws-sdk.

我找到了一种使用aws-sdk.

var aws = require('aws-sdk');
var lambda = new aws.Lambda({
  region: 'us-west-2' //change to your region
});

lambda.invoke({
  FunctionName: 'name_of_your_lambda_function',
  Payload: JSON.stringify(event, null, 2) // pass params
}, function(error, data) {
  if (error) {
    context.done('error', error);
  }
  if(data.Payload){
   context.succeed(data.Payload)
  }
});

You can find the doc here: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html

您可以在此处找到该文档:http: //docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html

回答by kixorz

You should chain your Lambda functionsvia SNS. This approach provides good performance, latency and scalability for minimal effort.

你应该链接你的Lambda functionsvia SNS。这种方法以最少的努力提供了良好的性能、延迟和可扩展性。

Your first Lambdapublishes messages to your SNS Topicand the second Lambdais subscribed to this topic. As soon as messages arrive in the topic, second Lambdagets executed with the message as it's input parameter.

您的第一个Lambda向您发布消息,SNS Topic第二个Lambda订阅此主题。一旦消息到达主题, secondLambda就会使用该消息作为输入参数执行。

See Invoking Lambda functions using Amazon SNS notifications.

请参阅使用 Amazon SNS 通知调用 Lambda 函数

You can also use this approach to Invoke cross-account Lambda functions via SNS.

您还可以使用此方法通过 SNS 调用跨账户 Lambda 函数

回答by blueskin

here's a sample code for python,

这是python的示例代码,

from boto3 import client as boto3_client
from datetime import datetime
import json

lambda_client = boto3_client('lambda')

def lambda_handler(event, context):
    msg = {"key":"new_invocation", "at": datetime.now()}
    invoke_response = lambda_client.invoke(FunctionName="another_lambda_",
                                           InvocationType='Event',
                                           Payload=json.dumps(msg))
    print(invoke_response)

Btw, you would need to add a policy like this to your lambda role as well

顺便说一句,您还需要将这样的策略添加到您的 lambda 角色中

   {
        "Sid": "Stmt1234567890",
        "Effect": "Allow",
        "Action": [
            "lambda:InvokeFunction"
        ],
        "Resource": "*"
    }

回答by dustinnoe

Since this question was asked, Amazon has released Step Functions (https://aws.amazon.com/step-functions/).

自从提出这个问题后,亚马逊就发布了 Step Functions ( https://aws.amazon.com/step-functions/)。

One of the core principles behind AWS Lambda is that you can focus more on business logic and less on the application logic that ties it all together. Step functions allows you to orchestrate complex interactions between functions without having to write the code to do it.

AWS Lambda 背后的核心原则之一是,您可以更多地关注业务逻辑,而不是将它们联系在一起的应用程序逻辑。Step Functions 允许您编排函数之间的复杂交互,而无需编写代码来执行此操作。

回答by Trilok Nagvenkar

This solution is done using boto3 and Python:

此解决方案是使用 boto3 和 Python 完成的:

import boto3
import json

invokeLambda = boto3.client('lambda', region_name='eu-west-1')

def lambda_handler(event, context):
    invokeLambda.invoke(FunctionName = 'function_name', InvocationType = 'RequestResponse', Payload = json.dumps(event))

    return True

回答by Ben Iggulden

I was looking at cutting out SNS until I saw this in the Lambda client docs (Java version):

我一直在考虑删除 SNS,直到我在Lambda 客户端文档(Java 版本)中看到这一点:

Client for accessing AWS Lambda. All service calls made using this client are blocking, and will not return until the service call completes.

用于访问 AWS Lambda 的客户端。使用此客户端进行的所有服务调用都是阻塞的,并且在服务调用完成之前不会返回。

So SNS has an obvious advantage: it's asynchronous. Your lambda won't wait for the subsequent lambda to complete.

所以SNS有一个明显的优势:它是异步的。您的 lambda 不会等待后续 lambda 完成。

回答by Sunil Kapil

Amazon has introduced steps functions in AWS lambda in 2016. I think, now it's more convenient to use steps function as it's really easy to use them. You can build a state machine with two lambda functions as:

亚马逊在 2016 年就在 AWS lambda 中引入了 Steps 函数。我认为,现在使用 Steps 函数更方便,因为它真的很容易使用。您可以使用两个 lambda 函数构建一个状态机,如下所示:

  • to produces a quote
  • turns a quote into an order
  • 产生报价
  • 将报价转化为订单

You can easily do that as below:

您可以轻松地做到这一点,如下所示:

Here you can have first state for produces a quote and another to turns into order

在这里你可以有第一个状态产生一个报价和另一个变成订单

{
  Comment: "Produce a quote and turns into an order",
  StartAt: "ProduceQuote",
  States: {
    ProduceQuote: {
      "Type": Task,
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:ProduceQuote",
      "next": TurnsToOrder
    }
    TurnsToOrder: {
      Type: Task,
      Resource: "arn:aws:lambda:us-east-1:123456789012:function:ProduceQuote",
      end: true
    }
  }
}

Steps functions makes it really easy to write multiple lambda functions and run in sequence or in parallel. You can get more information about lambda steps functions here: Steps Functions

Steps 函数使编写多个 lambda 函数并按顺序或并行运行变得非常容易。您可以在此处获取有关 lambda 步骤函数的更多信息: 步骤函数

回答by Suyash

In java, we can do as follows :

在java中,我们可以这样做:

AWSLambdaAsync awsLambdaAsync = AWSLambdaAsyncClientBuilder.standard().withRegion("us-east-1").build();

InvokeRequest invokeRequest = new InvokeRequest();
invokeRequest.withFunctionName("youLambdaFunctionNameToCall").withPayload(payload);

InvokeResult invokeResult = awsLambdaAsync.invoke(invokeRequest); 

Here, payload is your stringifiedjava object which needs to be passed as Json object to another lambda in case you need to pass some information from calling lambda to called lambda.

在这里,payload 是字符串化的java 对象,它需要作为 Json 对象传递给另一个 lambda,以防您需要将一些信息从调用 lambda 传递到被调用 lambda。

回答by antonio

I was working with the answer provided by blueskinbut I could not read the Payload response because the InvocationType='Event'is async, so I changed as InvocationType='RequestResponse' and now all works good.

我正在使用blueskin提供的答案,但我无法读取有效负载响应,因为InvocationType='Event'async,所以我更改为 InvocationType='RequestResponse' ,现在一切正常。

回答by Mike

You might be able to make use of the Async.js Waterfall feature - see the bottom part of the big code chunk in Step 3 of this document for an example:

您或许可以使用 Async.js 瀑布功能 - 请参阅本文档第 3 步中大代码块的底部以获取示例:

https://aws.amazon.com/blogs/compute/better-together-amazon-ecs-and-aws-lambda/

https://aws.amazon.com/blogs/compute/better-together-amazon-ecs-and-aws-lambda/