简体   繁体   English

如何创建自定义事件以在无服务器上触发 function

[英]How create a custom event to trigger a function on serverless

I have a function that make a request each 5 minutes and get an array of result.我有一个 function 每 5 分钟发出一个请求并获得一组结果。 I want to each item in this array call another lambda to process individually.我希望这个数组中的每个项目都调用另一个 lambda 来单独处理。

How can I create a custom trigger to call a function when this array is receive?收到此数组时,如何创建自定义触发器来调用 function? I am using Nodejs with serverless framework.我正在使用带有无服务器框架的 Nodejs。

PS: If I simply make a call http for each item in array, how can I get the url of the another function dinamically? PS:如果我只是为数组中的每个项目调用 http ,我怎样才能动态地获得另一个 function 的 url ?

Thanks!谢谢!

You should be able to use the AWS SDK to call the Lambda using the invoke method:您应该能够使用 AWS SDK 使用调用方法调用 Lambda:

var params = {
  FunctionName: "my-function", 
  Payload: <Binary String>, 
  Qualifier: "1"
 };
 lambda.invoke(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else     console.log(data);           // successful response
   /*
   data = {
    Payload: <Binary String>, 
    StatusCode: 200
   }
   */
 });

https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html#invoke-property https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html#invoke-property

This lets you call as many Lambda functions as you need from within the current one.这使您可以从当前函数中调用尽可能多的 Lambda 函数。 However, I would recommend a different technique since this does not handle errors very cleanly and assumes you will always use the one and only Lambnda to process a small number of items in a small array.但是,我会推荐一种不同的技术,因为它不能非常干净地处理错误,并且假设您将始终使用唯一的 Lambnda 来处理小数组中的少量项目。 A better method can help handle errors better as we as handle an increase in volume better.更好的方法可以帮助更好地处理错误,因为我们可以更好地处理音量的增加。

In your serverless.yml file, have a function that process the items in your list get triggered by SNS (please name things correctly in your case):在您的 serverless.yml 文件中,有一个 function 处理列表中的项目由 SNS 触发(请根据您的情况正确命名):

functions:
  receiveItem:
    handler: fileName.receiveItem
    events:
      - sns: recieveItem

Then in the Lambda that has the array, add the item as a message into the SNS topic one at a time and you will then have Lambda functions spin up and process them.然后在具有数组的 Lambda 中,将项目作为消息一次添加到 SNS 主题中,然后您将让 Lambda 函数启动并处理它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM