对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

使用 Google Cloud 管理连接

您可以使用Google Cloud Platform FunctionsGoogle Cloud Platform Run 与Atlas集群交互。

使用以下最佳实践正确管理 Google Cloud 函数和 Atlas 之间的连接:

  • 使用全局范围的数据库连接而不是函数范围的数据库连接,以创建 Cloud Function。

    请勿在每次调用函数时都定义新的客户端对象。这样做会导致驱动程序在每次函数调用时创建一个新的数据库连接。这可能会产生高昂的成本,并可能导致应用程序超出数据库连接限制。为获得最佳性能,请遵循以下准则:

    1. 创建一次客户端对象。

    2. 存储该对象,以便函数可以跨函数调用重复使用客户端。

    连接示例会重复使用现有数据库连接来加快与数据库的通信,并将与数据库的连接数保持在与应用程序流量相当的合理水平。

    If you have a function that connects to a sharded cluster with many shards, you might experience performance issues. For example, with a ten shard Atlas cluster, the driver connects to all thirty mongos instances by default. You can use the srvMaxHosts option in your connection string to set the maximum number of hosts that the driver connects to. To improve driver performance, set srvMaxHosts=3. For example:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.mongodb.net/?retryWrites=true&w=majority&srvMaxHosts=3

    要了解详细信息,请参阅连接选项

  • 限制对 Atlas 集群的网络访问。

    在 Atlas 集群和 Google Cloud 函数之间使用网络对等连接私有端点,通过私有网络连接到 Atlas 集群,以便仅允许使用 IP 访问列表中的私有 IP 地址。

    如果您不使用专用网络,请考虑通过 NAT 网关连接到Atlas 集群。否则,您必须允许所有IP地址 (... /)访问权限Atlas0 0000集群。

    警告

    Adding the /0 CIDR, such as 0.0.0.0/0, allows access from anywhere. This configuration can expose your deployment to unauthorized access, data exfiltration, and other malicious activity. Restrict access to trusted IP addresses or CIDR ranges whenever possible, and use strong credentials for all database users when allowing access from the public Internet.

    注意

    如果您将任何 IPv4 /0 CIDR(例如 0.0.0.0/010.0.0.0/0)添加到项目访问列表中,Atlas 会向所有直接被授予该项目角色的用户发送告警邮件;对于通过团队成员身份间接获得项目角色的用户(前提是该团队已被授予项目角色),Atlas 也会发送告警邮件。

  • maxIdleTimeMS 设置为 ,可在60000 1分钟的空闲时间后自动关闭连接。调整maxIdleTimeMS 有助于减少无服务器函数发生超时错误的概率。
  • 配置并发。创建新 Google Cloud 函数时:

    • 选择可以处理多个并发请求的2nd gen环境。 2 nd gen 还允许函数与许多并发调用股票单个MongoClient ,从而减少服务器上的连接负载。

    • 增加并发设置,尽量减少冷启动并改善延迟。

    注意

    如果增加并发设置,您可能需要增加 CPU 以获得最佳性能。如要了解更多信息,请参阅并发。

以下示例将 Node.js Google Cloud 函数连接到 Atlas 部署。请将 <YOUR-ATLAS-CONNECTION-STRING> 替换为您的 Atlas 连接字符串。

const { MongoClient } = require('mongodb');
let client;
async function getConnection() {
if (!client) {
const client = new MongoClient('<YOUR-ATLAS-CONNECTION-STRING>');
client.on('connectionCreated', () => {
console.log('New connection created successfully.');
});
// Connect to the database in the global scope
await client.connect();
}
return client;
}
给本页内容打分