Lambda Function 如何呼叫另一個 Lambda Function?
實務上有些情況我們會需要從某個Lambda function去呼叫另一個Lambda function起來做事
例如, 處理客戶訂單的OrderLambdaFunction 處理完客戶訂購的請求後, 需要喚起處理付款的PaymentLambdaFunction
要達到這個目的有兩個方法
Lambda Invoke
這個方法最簡單, 使用aws-sdk就能呼叫另一個Lambda Function,但我們需要添加合適的Policy到OrderLambdaFunction使用的Role中
{
"Sid": "Stmt1234567890",
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": "*"
}
步驟1: IAM > Policies > Create Policy > JSON(建立Customized Policy)
步驟2: IAM > Roles > Your_Lambda_Role > Attach Policy
OrderLambdaFunction
exports.handler = (event, context, callback) => {
// TODO implement
lambda.invoke({
FunctionName: 'PaymentLambdaFunction',
Payload: JSON.stringify({}, null, 2) // pass params
}, function(error, data) {
if (error) {
console.log(error);
}
if(data.Payload){
console.log(data.Payload);
}
});
callback(null, 'Hello from Lambda');
};
var aws = require('aws-sdk');
var lambda = new aws.Lambda({
region: 'us-east-1' //change to your region
});
PaymentLambdaFunction
exports.handler = (event, context, callback) => {
// TODO implement
console.log("Hello from Lambda ");
callback(null, { Payload: { "data": "123"}});
};
SNS
這個作法是讓SNS作為兩個Lambda之間的溝同橋梁
定義好溝通的Topic之後, 只要其中一方發布訊息, SNS就能夠觸發訂閱的那方起來做事
RequestPayTopic
首先, 在Simple Notification Service需要建立一條Topic, 讓兩方可以做溝通
OrderLambdaFunction
發布訊息到指定的Topic: RequestPayTopic
Source code
exports.handler = (event, context, callback) => {
// TODO implement
var sns = new aws.SNS();
console.log('start sns function')
sns.publish({
Message: 'Process the bill',
TopicArn: process.env.TopicArn
}, function(err, data) {
if (err) {
console.log(err.stack);
return;
}
console.log('push sent');
console.log(data);
});
callback(null, 'Hello from Lambda');
};
var aws = require('aws-sdk');
Policy
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sns:Publish"
],
"Resource": [
"*"
]
}
]
}
PaymentLambdaFunction
訂閱 RequestPayTopic, 作為Lambda的觸發條件, SNS會在收到訊息後去觸發PaymentLambdaFunction
留言
張貼留言