来自使用 AWS Lambda 函数的最佳实践 https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html:
利用执行上下文重用来提高函数的性能。在函数处理程序之外初始化 SDK 客户端和数据库连接,[...]
我想实现这个原则来改进我的 lambda 函数,其中每次调用函数时都会初始化和关闭数据库句柄。举个例子:
def lambda_handler(event, context):
# Open a connection to the database
db_handle = connect_database()
# Do something with the database
result = perform_actions(db_handle)
# Clean up, close the connection
db_handle.close()
# Return the result
return result
根据我对AWS文档的理解,代码应该优化如下:
# Initialize the database connection outside the handler
db_handle = conn_database()
def lambda_handler(event, context):
# Do something with the database and return the result
return perform_actions(db_handle)
这将导致db_handle.close()
方法未被调用,因此可能泄漏连接。
在将 AWS Lambda 与 Python 结合使用时,我应该如何处理此类资源的清理?
很多人都在寻找与你相同的东西。我相信目前这是不可能的。但我们可以从数据库方面来处理这个问题。
看一眼this one https://stackoverflow.com/questions/56013578/is-it-possible-to-intercept-kill-signals-to-close-db-connections-right-before-a
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)