AWS Lambda to run in background even after sending response to API Gateway

梦想与她 提交于 2019-12-04 17:04:07

问题


I have searched all through the net but didn't find a solution of how to make this functionality get succeeded. Require help.

My requirement is: I want a that if I trigger an aws lambda function written in node.js and uses an aws-serverless-express module must send back response quickly to API gateway but still should not exit and still run in the backend and we could see cloud watch logs. It must be asynchronous.

The code snippet is:

    app.get('/check', function(req, res){
     method.invoke(req)
     res.status(200).send('success')
   })

I did and checked like this but the lambda function gets stopped and returns the response to api gateway it didn't even runs the method.invoke() function in backend.

Please correct me if anything I am understanding or doing wrong. I checked with this link: Invoke AWS Lambda and return response to API Gateway asyncronously

Is it the only way to do this problem. Creating two lambda functions.


回答1:


You can achieve this by using AWS Lambda Step functions, connected to API Gateway, having parallel execution of branches with two lambda functions, where one returns a response to API Gateway and other executes asynchronously.




回答2:


Besides Step Functions, you could just invoke another Lambda function using the SDK built-in to the Lambda environment.

I'm no expert in express or NodeJS but I would also think there should be a way to send the HTTP response back and still continue code execution.




回答3:


Step function seems the best solution here. See @Ashan's reply. Apart from that you can use the new invoke method in lambda nodejs sdk. Note that invokeAsync is now deprecated. You can set InvocationType to Event See the example below. which is taken from here

var params = {
  ClientContext: "MyApp", 
  FunctionName: "MyFunction", 
  InvocationType: "Event", 
  LogType: "Tail", 
  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 = {
    FunctionError: "", 
    LogResult: "", 
    Payload: <Binary String>, 
    StatusCode: 123
   }
   */
 }); 

one example use case is, first function would return an immediate response, and it would trigger another lambda function which would execute the tasks and eventually may be call a webhook.



来源:https://stackoverflow.com/questions/44668605/aws-lambda-to-run-in-background-even-after-sending-response-to-api-gateway

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