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.

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

报告相同问题?