我需要lambda来正常关闭并登录到外部系统。在查看有关此问题的一些文献之后,我使用线程达成了以下解决方案:

def lambda_handler(event, context):

    threshold_millis = 10 * 1000  # leave when there are only 10 seconds left
    que = queue.Queue()
    t = threading.Thread(target=lambda q, ev: q.put(do_work(ev)), args=(que, event))
    t.daemon = True
    t.start()

    while True:
        if context.get_remaining_time_in_millis() < threshold_millis:
            # Do some logging notifying the timeout
            return {
                "isBase64Encoded": False,
                "statusCode": 408,
                "headers": {'Content-Type': "application/json"},
                "body": "Request timed out"
            }

        elif not t.isAlive():
            response = que.get()
            return response

        time.sleep(1)

尽管它可行,但我想知道:是否有比该方法更好的方法来优雅地处理AWS Lambda中的超时?

最佳答案

观看get_remaining_time_in_millis是抢占lambda超时的最佳/建议方式;不会调用任何特殊事件来让您知道您将要超时。

在不知 Prop 体细节的情况下,您可以通过查看接收错误花费了多长时间来推断客户端超时。但是,我希望您对lambda进行明确说明。

关于Python-如何在AWS Lambda中优雅地处理超时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50484019/

10-16 11:53