duanjie6912 2018-05-16 07:01
浏览 17
已采纳

当处理函数退出时,aws-lambda中的goroutines会发生什么?

The question originates in: how much work can I do in the background, when the response has already been sent. For instance: I just want to receive data, tell the client 'ok', and proceed with some database operations that may take some time.

package main

import (
        "fmt"
        "context"
        "github.com/aws/aws-lambda-go/lambda"
)

type MyEvent struct {
        Name string `json:"name"`
}

func HandleRequest(ctx context.Context, name MyEvent) (string, error) {
        go RecordQuery(name)
        return fmt.Sprintf("Hello %s!", name.Name ), nil
}

func RecordQuery(name MyEvent) {
        // insert stuff in the database, mark user active,
        // log activity, etc..
}

func main() {
        lambda.Start(HandleRequest)
}

Can we count on the goroutine to be able to do its work?

  • 写回答

1条回答 默认 最新

  • doujie4787 2018-05-16 07:01
    关注

    It turns out we can't assume the code will run.

    Example implementation:

    var alreadyLogging bool
    
    func RecordQuery(name MyEvent) {
        if alreadyLogging {
            return
        }
        alreadyLogging = true
        for i := 0; ; i++ {
            time.Sleep(time.Second)
            log.Print("Still here ", i)
        }
    }
    

    Behaviour: as long as the container where the lambda is running is receiving requests, the goroutine will be executed. But all code will stop when the container is no longer receiving requests.

    Possible output (in cloudwatch):

    2018/05/16 08:50:46 Still here 70
    2018/05/16 08:50:47 Still here 71
    2018/05/16 08:50:48 Still here 72
    2018/05/16 08:50:49 Still here 73
    2018/05/16 08:51:36 Still here 74
    2018/05/16 08:51:37 Still here 75
    2018/05/16 08:51:38 Still here 76
    

    Note that in the Node.js Programming Model, you can request AWS Lambda to freeze the process soon after the callback is called, even if there are events in the event loop: The Context Object Properties.

    It would be interesting to see some use cases for this API.

    Update: in Node.js, as soon as you connect to databases, you'll have a non-empty event queue. That's why this setting is available.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)