可扩展性 Azure Function/AWS Lamda

Scalability Azure Function/AWS Lamda

我正在考虑使用 Azure Function/AWS Lambda/Serverless 作为后端。它如何扩展到数百万个请求,代码必须打开数据库。我了解它不会重用连接?

例如调用是这样的。

using (var db = new Database(..,))
{
  // db calls
}

它是如何横向扩展的,它是否高效?

你的问题有点不准确。我不太了解 Azure,但对于 AWS Lambda,它的扩展性很好。如果您有 100 万个并发请求,Lambda 将为每个请求创建一个实例。请注意,每个区域有 1000 个并发执行 a default limit,但可以通过支持请求增加这些执行。

在发出第一个请求后,容器可以重新使用。有一个 blog post 解释它是如何工作的。虽然不建议您尝试在容器内缓冲您的连接。根据数据库和驱动程序的不同,您的连接可能会在冻结期间失效,也可能仍然有效。对于其中一个 Lambda,我使用缓冲效果很好。您应该注意,如果您没有正确关闭连接,这可能会导致您的数据库服务器 泄漏 ,当然您应该 验证 连接在再次使用之前。

使用 Java 我将连接放入 class 的范围内,并在我的处理程序中检查连接是否已经初始化,例如:

public class LambdaHandler implements RequestStreamHandler {
  private Connection con = null;

  public void handleRequest(InputStream inputStream,
      OutputStream outputStream, Context context) {
    if (con == null) {
      con = getConnection(context);
    } else {
      con = validateConnection(context, con);
    }
  }

您可能可以使用您使用的语言来做同样的事情。如果 Azure Functions 的工作方式与 AWS Lambda 非常相似,我不会感到惊讶,但您最好查看文档以进行验证。

当谈到在 AWS 中使用 lambda 中的数据库连接时,您应该阅读有关 container execution model of lambda 的内容。调用 lambda 时,AWS 会启动一个容器以 运行 处理程序函数中的代码。因此,如果您在处理函数之外定义数据库连接,它将在 Lambda 函数的调用之间共享。你可以在上面的 link 中找到它。

Any declarations in your Lambda function code (outside the handler code, see Programming Model) remains initialized, providing additional optimization when the function is invoked again. For example, if your Lambda function establishes a database connection, instead of reestablishing the connection, the original connection is used in subsequent invocations. You can add logic in your code to check if a connection already exists before creating one.

const pg = require('pg');
const client = new pg.Client(<connection_string>);

exports.handler = (event, context, cb) => {  
  client.query('SELECT * FROM users WHERE ', (err, users) => {
    // Do stuff with users
    cb(null); // Finish the function cleanly
});
};

参考 this 博客 post。

但有一个警告。

When you write your Lambda function code, do not assume that AWS Lambda always reuses the container because AWS Lambda may choose not to reuse the container. Depending on various other factors, AWS Lambda may simply create a new container instead of reusing an existing container.

此外,您可以创建计划作业来预热 lambda 函数。 (每 5 分钟 运行 秒)