How to return the function result and perform additional operations in aws lambda

huangapple go评论163阅读模式
英文:

How to return the function result and perform additional operations in aws lambda

问题

假设我有以下的工作流程:

func get_result(event) { return result(event) }
func post_result_operations(event) { /* 进行一些日志记录 */ }
func lambda_handler(event) {
      return get_result(event)
      post_result_operations(event)
}

有没有办法创建一个 Lambda 函数,使我可以调用 get_result 函数并返回其值,然后执行 post_result_operations 函数。我的想法是通过 API 调用 Lambda 函数,让函数快速返回结果,然后在返回结果后执行其他操作。在 Node.js 或 Golang 中有没有实现这个的方法。在 Golang 中,我们可以像下面这样做,但我不确定它是否有效。

func lambda_handler(event) {
     defer post_result_operations(event)
     return get_result(event)
}

希望能得到帮助。

英文:

Suppose I have the following workflow

func get_result(event) { return result(event) }
func post_result_operations(event) { /* do some logging */ }
func lambda_handler(event) {
      return get_result(event)
      post_result_operations(event)
}

Is there a way to create a lambda function such that I can call the get_result function and returns its value and then do the post_result_operations. The idea is that I would want to invoke my lambda function through an API and have the function return the result quickly and then do the additional operations after the result is returned. Is there a way to accomplish this in nodejs or Golang. In Golang, we can have something like the following, but I am not sure it will work.

func lambda_handler(event) {
     defer post_result_operations(event)
     return get_result(event)
}

Any help would be appreciated

答案1

得分: 1

如果你只想记录日志,你可以查看Lambda扩展。不过,函数退出后你只能运行有限的时间。

一旦Lambda函数返回,代码就会停止,所以之后可能发生的任何事情都不会发生。解决这个问题的最佳方法是通过类似SQS的方式使处理过程异步化。你可以将事件发送到一个SQS队列,然后由另一个Lambda函数来处理,并返回结果。类似这样的代码:

func get_result(event) { return result(event) }
func send_to_sqs(event) { /* 将消息发送到SQS */ }
func lambda_handler(event) {
      send_to_sqs(event)
      return get_result(event)
}
英文:

If all you want to do is logging you could look into Lambda extensions. There is a limited amount of time you can run after the function exits, though.

Once a Lambda function has returned the code is stopped, so anything that might happen after would not happen. The best approach to this is to make your processing asynchronous, via something like SQS. You can sned the event on to an SQS queue where a different Lambda function can process it, and then return your result. Something like this:

func get_result(event) { return result(event) }
func send_to_sqs(event) { /* send the message to SQS */ }
func lambda_handler(event) {
      send_to_sqs(event)
      return get_result(event)
}

huangapple
  • 本文由 发表于 2021年5月20日 23:59:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/67623997.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定