node.js - 在 AWS lambda 中调用嵌套函数
问题描述
我有一个 AWS Lambda 函数来检查站点是否在线
var http = require('https');
var url = 'https://www.google.com';
exports.handler = function(event, context) {
http.get(url, function(res) {
console.log("Got response: " + res.statusCode);
context.succeed();
}).on('error', function(e) {
console.log("Got error: " + e.message);
context.done(null, 'FAILURE');
});
}
如果网站离线,我想重新启动 EC2 实例。这是重启 EC2 的 Lambda 函数:
var AWS = require('aws-sdk');
exports.handler = function(event, context) {
var ec2 = new AWS.EC2({region: 'us-east-1'});
ec2.rebootInstances({InstanceIds : ['i-xxxxxxxxxxxxxxx'] },function (err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
context.done(err,data);
});
};
这两个功能都有效。现在我尝试在 https 请求失败时调用 ec2 reboot 函数。
我对 node.js 和 aws 的经验非常有限,所以我尝试了很多不同的方法,但没有结果。
有人可以指出我正确的方向吗?
解决方案
您可以使用调用函数调用 lambda。
function checkWebsite(url, callback) {
https
.get(url, function(res) {
console.log(url, res.statusCode);
return callback(res.statusCode === 200);
})
.on("error", function(e) {
return callback(false);
});
}
var http = require('https');
exports.handler = function(event, context, callback) {
var url = 'https://www.google.com';
checkWebsite(url, (check) => {
if (!check) {
const lambda = new AWS.Lambda();
const params = {
FunctionName: "my-function",
Payload: '{"instanceId":"instance-1233x5"}'
};
lambda.invoke(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
// handle error/ success
// if you return the error, the lambda will be retried, hence returning a successful response
callback(null, 'successfully rebooted the instance')
});
} else {
callback(null, 'successfully completed')
}
})
}
推荐阅读
- mysql - MySQL根据多个条件查找第一行
- postgresql - 错误 {"type":"pg-client","timestamp":"2021-08-02T05:04:50.035+0000","level":"warn","detail":{"message":"postgres 连接失败,重试(0)。"}}
- python - Python while循环令牌未更新
- credentials - 如何创建自定义 VC 类型
- azure-ad-b2c - MFA 手机号码字段限制
- python - 将列中的字符串列表转换为单独的列Python
- typescript - 相同的对象名称扩展接口打字稿
- javascript - 需要帮助以使只有两张卡可以点击,直到它们匹配
- arrays - 是否可以在两个不同的屏幕中使用相同的数组进行反应导航?
- arrays - 基于属性 ReactJs 显示对象数组