如何配置适用于 Cosmos DB 的 Azure Functions 触发器使用的连接策略How to configure the connection policy used by Azure Functions trigger for Cosmos DB

本文介绍在使用适用于 Cosmos DB 的 Azure Functions 触发器连接到 Azure Cosmos 帐户时如何配置连接策略。This article describes how you can configure the connection policy when using the Azure Functions trigger for Cosmos DB to connect to your Azure Cosmos account.

连接策略为什么很重要?Why is the connection policy important?

有两种连接模式 - Direct(直接)模式和 Gateway(网关)模式。There are two connection modes - Direct mode and Gateway mode. 若要详细了解这些连接模式,请参阅性能提示一文。To learn more about these connection modes, see the performance tips article. 默认情况下,网关用于在适用于 Cosmos DB 的 Azure Functions 触发器中建立所有连接。By default, Gateway is used to establish all connections on the Azure Functions trigger for Cosmos DB. 但是,对于性能驱动的方案,它可能不是最佳选项。However, it might not be the best option for performance-driven scenarios.

更改连接模式和协议Changing the connection mode and protocol

有两个密钥配置设置可用于配置客户端连接策略 - 连接模式连接协议There are two key configuration settings available to configure the client connection policy - the connection mode and the connection protocol. 可以更改 Cosmos DB 的 Azure Functions 触发器和所有 Azure Cosmos DB 绑定使用的默认连接模式与协议。You can change the default connection mode and protocol used by the Azure Functions trigger for Cosmos DB and all the Azure Cosmos DB bindings). 若要更改默认设置,需要在 Azure Functions 项目或 Azure Functions 应用中找到 host.json 文件,并添加以下附加设置To change the default settings, you need to locate the host.json file in your Azure Functions project or Azure Functions App and add the following extra setting:

{
  "cosmosDB": {
    "connectionMode": "Direct",
    "protocol": "Tcp"
  }
}

其中,connectionMode 必须包含所需的连接模式(Direct 或 Gateway),protocol 必须包含所需的连接协议(Tcp 或 Https)。Where connectionMode must have the desired connection mode (Direct or Gateway) and protocol the desired connection protocol (Tcp or Https).

如果 Azure Functions 项目正在使用 Azure Functions V1 运行时(配置名称略有不同),则应使用 documentDB 而不是 cosmosDBIf your Azure Functions project is working with Azure Functions V1 runtime, the configuration has a slight name difference, you should use documentDB instead of cosmosDB:

{
  "documentDB": {
    "connectionMode": "Direct",
    "protocol": "Tcp"
  }
}

Note

使用 Azure Functions 消耗计划托管计划时,每个实例可以维护的套接字连接数量有限制。When working with Azure Functions Consumption Plan Hosting plan, each instance has a limit in the amount of Socket Connections that it can maintain. 使用 Direct/TCP 模式时,根据设计会创建更多的连接,这可能会达到消耗计划限制,在这种情况下,可以使用 Gateway 模式,或者以应用服务模式运行 Azure Functions。When working with Direct / TCP mode, by design more connections are created and can hit the Consumption Plan limit, in which case you can either use Gateway mode or run your Azure Functions in App Service Mode.

后续步骤Next steps