Invoke multiple aws lambda functions

为君一笑 提交于 2019-12-03 03:56:27

I wouldn't recommend using direct invoke to launch your functions. Instead you should consider creating an SNS Topic and subscribing your Lambda functions to this topic. Once a message is published to your topic, all functions will fire at the same time. This solution is also easily scalable.

See more information at official documentation Invoking Lambda functions using Amazon SNS notifications

A simple way to do it is to use the AWS sdk to invoke the lambda function.

The solution would look different depending on what sdk you use. If using the Node sdk I would suggest promisifying the sdk with a Promise library like for example Bluebird.

The code would look something like:

const Promise = require('bluebird');
const AWS = require('aws-sdk');
const lambda = Promise.promisifyAll(new AWS.Lambda({ apiVersion: '2015-03-31' }));

lambda.invokeAsync({FunctionName: 'FirstLambdaFunction'})
  .then(() => {
    // handle successful response from first lambda
    return lambda.invokeAsync({FunctionName: 'SecondLambdaFunction'});
  })
  .then(() => lambda.invokeAsync({FunctionName: 'ThirdLambdaFunction'}))
  .catch(err => {
    // Handle error response  
  );

The reason why I like this approach is that you own the context of all the lambdas and can decide to do whatever you like with the different responses.

With python:

from boto3 import client as botoClient
import json
lambdas = botoClient("lambda")

def lambda_handler(event, context):
    response1 = lambdas.invoke(FunctionName="myLambda1", InvocationType="RequestResponse", Payload=json.dumps(event));
    response2 = lambdas.invoke(FunctionName="myLambda2", InvocationType="RequestResponse", Payload=json.dumps(event));

Just call the next Lambda function at the end of each function?

Use http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda_20141111.html#invokeAsync-property if you are using Node.js/JavaScript.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!