我编写了一个AWS lambda函数,用于在上传S3对象时发送文本消息。我已经确认了订阅,我可以收到SNS控制台发送的测试消息。
当我测试lambda时,所有日志都说方法成功,但没有任何儿子消息到达。这是函数(主要是示例模板,但在本文中为了安全性而改变了我的主题)。任何有关测试/尝试的事情的提示都会受到赞赏。
console.log('Loading function');
var aws = require('aws-sdk');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });
exports.handler = function(event, context) {
var bucket = event.Records[0].s3.bucket.name;
var key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
var params = {
Bucket: bucket,
Key: key
};
var sns = new aws.SNS();
console.log('start of brians sns function')
var pubResult = sns.publish({
Message: 'Test publish to SNS from Lambda',
TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:lambdatop'
}, function(err, data) {
if (err) {
console.log(err.stack);
return;
}
console.log('push sent');
console.log(data);
});
console.log('after sns publish:')
console.log(pubResult)
context.done(null, 'Brians Function Finished!');
};
答案 0 :(得分:6)
您在致电context.done()
后立即致电publish()
。 publish()函数是一个异步调用,你不等待它完成。另外,我不认为您的变量pubResult
包含您期望的变量。
试试这个:
console.log('Loading function');
var aws = require('aws-sdk');
exports.handler = function(event, context) {
var sns = new aws.SNS();
console.log('start of brians sns function')
sns.publish({
Message: 'Test publish to SNS from Lambda',
TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:lambdatop'
}, function(err, data) {
if (err) {
console.log(err.stack);
// Notify Lambda that we are finished, but with errors
context.done(err, 'Brians Function Finished with Errors!');
return;
}
console.log('push sent');
console.log(data);
// Notify Lambda that we are finished
context.done(null, 'Brians Function Finished!');
});
};
答案 1 :(得分:0)
解决此问题的另一种方法是将SNS Publish包裹在Promise中,等待从Lambda处理程序中解决该问题。
exports.handler = async (event) => {
await publishSNS(record, process.env.TOPIC_ARN);
}
async function publishSNS(payload, topicArn) {
await SNS.publish({
Message: JSON.stringify(payload),
TargetArn: topicArn
}).promise().then((data) => {
console.log('SNS push succeeded: ', data);
}).catch((err) => {
console.error(err);
});
}