Overview
本页介绍了C驱动程序中可用的连接选项,并解释了如何将它们应用于MongoDB连接。
如何指定连接选项
以下部分介绍了指定连接选项的方法。
使用连接字符串
如果将连接字符串传递给 monogoc_client_t 结构,则可以将连接选项作为 <name>=<value> 对包含在该 string 中。在以下示例中,连接字符串包含值为 60000 的 connectTimeoutMS 选项和值为 true 的 tls 选项:
mongoc_init(); // Specifies the connection options in the connection string const char *uri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true"; // Creates a new client mongoc_client_t *client = mongoc_client_new_from_uri_with_error(uri, &error); if (!client) { fprintf(stderr, "%s\n", error.message); goto cleanup; } // Use client... cleanup: mongoc_client_destroy(client); mongoc_uri_destroy(uri);
To learn more about the options that you can specify in a connection string, see Connection String Options in the MongoDB Server manual.
使用 URI 选项API
您可以使用 URI 选项在代码中而不是在连接字符串中配置连接设置。以这种方式配置连接可以更轻松地在运行时更改设置,帮助您在编译期间捕获错误,并提供比连接字符串更多的配置选项。
要使用 URI 选项设立连接选项,请执行以下步骤:
使用连接字符串创建一个
mongoc_uri_t结构使用 URI 选项函数指定所需的连接选项
创建具有该 URI 的新客户端,方法是将 URI 传递给
mongoc_client_new_from_uri()
以下代码示例展示了如何执行上述步骤:
mongoc_uri_t *uri = mongoc_uri_new_with_error("mongodb+srv://localhost:27017/", &error); if (!uri) { fprintf(stderr, "%s\n", error.message); goto cleanup; } // Specifies the connection options by using the URI options API if (!mongoc_uri_set_option_as_int32(uri, MONGOC_URI_CONNECTTIMEOUTMS, 60000)) { fprintf(stderr, "Failed to set '%s'\n", MONGOC_URI_CONNECTTIMEOUTMS); goto cleanup; } if (!mongoc_uri_set_option_as_bool(uri, MONGOC_URI_TLS, true)) { fprintf(stderr, "Failed to set '%s'\n", MONGOC_URI_TLS); goto cleanup; } // Creates a new client client = mongoc_client_new_from_uri_with_error(uri, &error); if (!client) { fprintf(stderr, "%s\n", error.message); goto cleanup; } // Use client... cleanup: mongoc_client_destroy(client); mongoc_uri_destroy(uri);
连接选项
以下部分描述了C驱动程序中可用的连接选项,以及如何直接使用连接字符串或 URI 选项来指定这些选项。
副本集选项
DirectConnection
指定是否强制将所有操作分派到托管。如果指定此选项,驱动程序将不接受 SRV 连接格式。您必须改用标准连接 URI 格式。要学习有关 SRV 连接和标准连接格式的更多信息,请参阅 连接字符串 指南。
默认值为 false。如果指定多个托管名,则必须将此属性设立为 false。
mongoc_uri_t *uri = mongoc_uri_new("mongodb://localhost:27017/?directConnection=true");
副本集(Replica Set)
要连接的副本集的名称。 默认值为 null。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?replicaSet=yourReplicaSet");
DirectConnection
指定是否强制将所有操作分派到托管。如果指定此选项,驱动程序将不接受 SRV 连接格式。您必须改用标准连接 URI 格式。要学习有关 SRV 连接和标准连接格式的更多信息,请参阅 连接字符串 指南。
默认值为 false。如果指定多个托管名,则必须将此属性设立为 false。
mongoc_uri_set_option_as_bool(uri, MONGOC_URI_DIRECTCONNECTION, true);
副本集(Replica Set)
要连接的副本集的名称。 默认值为 null。
mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_REPLICASET, "yourReplicaSet");
TLS 选项
启用 TLS
指定是否需要 TLS 来连接到服务器。如果使用 "mongodb+srv" 模式或指定其他 TLS 选项,则此选项默认为 true。否则,默认为 false。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true");
允许不安全的 TLS
指定是否尽可能放宽 TLS 约束。这可能包括允许无效证书或主机名不匹配。默认值为 false。
以下代码示例展示了如何将此选项设立为 true:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true&tlsAllowInvalidCertificates=true");
TLS 禁用证书撤销检查
是否在 TLS 握手期间禁用证书吊销检查。默认值为 false。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true&tlsDisableCertificateRevocationCheck=true");
SSL 选项
TLS/SSL 选项,包括客户端证书、撤销处理以及启用和禁用的 TLS/SSL 协议。默认值为 null。
此选项只能通过使用 URI 选项来设立。要学习;了解如何设立SSL 选项,请参阅 MongoC URI Option标签页下的 SSL 选项部分。
启用 TLS
指定是否需要 TLS 来连接到服务器。如果使用 "mongodb+srv" 模式或指定其他 TLS 选项,则此选项默认为 true。否则,默认为 false。
mongoc_uri_set_option_as_bool(uri, MONGOC_URI_TLS, true);
允许不安全的 TLS
指定是否尽可能放宽 TLS 约束。这可能包括允许无效证书或主机名不匹配。默认值为 false。
以下代码示例展示了如何将此选项设立为 true:
mongoc_uri_set_option_as_bool(uri, MONGOC_URI_TLSINSECURE, true);
TLS 禁用证书撤销检查
是否在 TLS 握手期间禁用证书吊销检查。默认值为 false。
mongoc_uri_set_option_as_bool(uri, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK, true);
SSL 选项
TLS/SSL 选项,包括客户端证书、撤销处理以及启用和禁用的 TLS/SSL 协议。默认值为 null。
如果将 SslSettings.CheckCertificateRevocation 设立为 false 并将 AllowInsecureTls 设立为 true,则 C 驱动程序会引发异常。
mongoc_client_t *client; mongoc_ssl_opt_t ssl_opts = {0}; ssl_opts.pem_file = "/path/to/client-cert.pem"; ssl_opts.pem_pwd = "password"; ssl_opts.ca_file = "/path/to/ca.pem"; ssl_opts.allow_invalid_hostname = false; mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true"); client = mongoc_client_new_from_uri(uri); mongoc_client_set_ssl_opts(client, &ssl_opts);
有关 TLS 选项的更多信息,请参阅配置传输层安全性 (TLS)指南。
超时选项
压缩选项
连接池选项
MaxConnectionPoolSize
驱动程序可以在其连接池创建的最大客户端或连接数。此计数包括正在使用的连接。默认值为 100。
mongoc_uri_set_option_as_int32(uri, MONGOC_URI_MAXPOOLSIZE, 150)
还可以使用 mongoc_client_pool_t 结构设立最大连接池大小:
mongoc_client_pool_t *pool = mongoc_client_pool_new(uri); // Specifies max pool size mongoc_client_pool_max_size(pool, 150);
WaitQueueTimeout
驱动程序在超时之前尝试从服务器的连接池检出连接的时间长度。
mongoc_uri_set_option_as_int32(uri, MONGOC_URI_WAITQUEUETIMEOUTMS, 30000);
要学习有关连接池的更多信息,请参阅连接池指南。
写关注选项
w
The w component of the write concern, which requests acknowledgment that the write operation has propagated to a specified number of MongoDB instances. The default value is "majority" or 1, depending on the number of arbiters and voting nodes. To learn more about the w option, see Write Concern in the MongoDB Server manual.
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?w=2");
wtimeout
The wtimeoutms component of the write concern, which specifies a time limit for the write concern. To learn more about the wtimeout option, see Write Concern in the MongoDB Server manual.
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?wTimeoutMS=5000");
日志
写关注(write concern)的 j 组件,请求确认MongoDB实例已写入磁盘上日志。默认值取决于 writeConcernMajorityJournalDefault 设置中的值。要学习;了解有关 j 选项的更多信息,请参阅MongoDB Server手册中的写关注。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?journal=true");
w
The w component of the write concern, which requests acknowledgment that the write operation has propagated to a specified number of MongoDB instances. The default value is "majority" or 1, depending on the number of arbiters and voting nodes. To learn more about the w option, see Write Concern in the MongoDB Server manual.
您可以使用 MONGOC_URI_W 选项设立w:
// Use the int32 version of the mongoc_uri_t set function to set integer values mongoc_uri_set_option_as_int32(uri, MONGOC_URI_W, 2); // Use the utf8 version of the mongoc_uri_t set function to set string values mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_W, "majority");
您还可以使用 mongoc_write_concern_t 结构设立w:
// Creates a write concern structure mongoc_write_concern_t *write_concern = mongoc_write_concern_new(); // Sets w=2 mongoc_write_concern_set_w(write_concern, 2); mongoc_client_set_write_concern(client, write_concern);
wtimeout
The wtimeoutms component of the write concern, which specifies a time limit for the write concern. To learn more about the wtimeout option, see Write Concern in the MongoDB Server manual.
您可以使用 MONGOC_URI_WTIMEOUTMS 选项设立wtimeoutms:
mongoc_uri_set_option_as_int32(uri, MONGOC_URI_WTIMEOUTMS, 5000);
您还可以使用 mongoc_write_concern_t 结构设立wtimeoutms:
// Creates a write concern structure mongoc_write_concern_t *write_concern = mongoc_write_concern_new(); // Sets w=2 mongoc_write_concern_set_wtimeout(write_concern, 5000); // Apply write concern to client mongoc_client_set_write_concern(client, write_concern);
日志
写关注(write concern)的 j 组件,请求确认MongoDB实例已写入磁盘上日志。默认值取决于 writeConcernMajorityJournalDefault 设置中的值。要学习;了解有关 j 选项的更多信息,请参阅MongoDB Server手册中的写关注。
您可以使用 MONGOC_URI_JOURNAL 选项设立journal:
mongoc_uri_set_option_as_bool(uri, MONGOC_URI_JOURNAL, true);
您还可以使用 mongoc_write_concern_t 结构设立journal:
// Creates a write concern structure mongoc_write_concern_t *write_concern = mongoc_write_concern_new(); // Sets journal to true mongoc_write_concern_set_journal(write_concern, true); // Apply write concern to client mongoc_client_set_write_concern(client, write_concern);
读关注选项
读关注级别
客户端的读关注(read concern)级别。有关更多信息,请参阅MongoDB Server手册中的读关注(read concern)参考。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?readConcernLevel=local");
读关注级别
客户端的读关注(read concern)级别。有关更多信息,请参阅MongoDB Server手册中的读关注(read concern)参考。
您可以使用 MONGOC_URI_READCONCERNLEVEL 选项设立读关注(read concern)级别:
mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_READCONCERNLEVEL, "local")
您还可以使用 mongoc_read_concern_t 结构设立读关注(read concern)级别:
mongoc_read_concern_t *read_concern = mongoc_read_concern_new(); // Set the read concern level to "local" mongoc_read_concern_set_level(read_concern, MONGOC_READ_CONCERN_LEVEL_LOCAL); mongoc_client_set_read_concern(client, read_concern);
读取偏好选项
读取偏好
The client's default read-preference settings. The default value is primary. See Read Preference in the MongoDB Server manual for more information.
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?readPreference=primaryPreferred");
maxstaleness
Max Staleness Seconds 表示从节点(secondary node from replica set)可能出现但仍有资格被选择服务器的最长复制延迟(以挂钟时间为单位)。maxStalenessSeconds 的最小允许值为 90 秒。此选项必须与非主节点读取偏好(read preference)一起使用。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?readPreference=secondary&maxStalenessSeconds=120");
LocalThreshold
服务器资格的延迟窗口。如果服务器的往返时间超过最快服务器的往返时间加上此值,则该服务器没有资格被选中。默认值为 15 毫秒。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?localThresholdMS=150");
读取偏好
The client's default read-preference settings. The default value is primary. See Read Preference in the MongoDB Server manual for more information.
您可以使用 mongoc_read_prefs_t 结构设立读取偏好(read preference):
mongoc_client_t *client = mongoc_client_new("mongodb+srv://localhost:27017/"); // Specifies the read preference mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new(MONGOC_READ_PRIMARY_PREFERRED); mongoc_client_set_read_prefs(client, read_prefs);
您还可以使用 MONGOC_URI_READPREFERENCE 选项设立读取偏好(read preference):
mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_READPREFERENCE, "primaryPreferred")
maxstaleness
Max Staleness Seconds 表示从节点(secondary node from replica set)可能出现但仍有资格被选择服务器的最长复制延迟(以挂钟时间为单位)。maxStalenessSeconds 的最小允许值为 90 秒。此选项必须与非主节点读取偏好(read preference)一起使用。
您可以使用 MONGOC_URI_MAXSTALENESSSECONDS 选项设立最大过时时间:
mongoc_uri_set_option_as_int32(uri, MONGOC_URI_MAXSTALENESSSECONDS, 120);
您还可以使用 mongoc_read_prefs_t 结构设立最大过时时间:
mongoc_client_t *client = mongoc_client_new("mongodb+srv://localhost:27017/"); mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new(MONGOC_READ_SECONDARY); // Specifies max staleness to 120 seconds mongoc_read_prefs_set_max_staleness_seconds(read_prefs, 120); mongoc_client_set_read_prefs(client, read_prefs);
LocalThreshold
服务器资格的延迟窗口。如果服务器的往返时间超过最快服务器的往返时间加上此值,则该服务器没有资格被选中。默认值为 15 毫秒。
mongoc_uri_set_option_as_int32(uri, MONGOC_URI_LOCALTHRESHOLDMS, 150);
身份验证选项
服务器选择和发现选项
心跳频率
服务器监控检查之间的时间间隔。必须大于或等于 500 毫秒。在池化(多线程)模式下,默认值为 10000 毫秒(10 秒);在非池化(单线程)模式下,默认值为 60000 毫秒(60 秒)。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?heartbeatFrequencyMS=5000");
ServerSelectionTimeout
驱动程序在超时之前尝试选择服务器的时间长度。默认值为 30000 毫秒(30 秒)。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?serverSelectionTimeoutMS=40000");
套接字检查间隔
仅应用于单线程客户端。如果套接字在这段时间内未被使用,驱动程序会在再次使用之前通过快速“hello”调用来检查连接。默认为 5000 毫秒(5 秒)。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?socketCheckIntervalMS=10000");
心跳频率
服务器监控检查之间的时间间隔。必须大于或等于 500 毫秒。在池化(多线程)模式下,默认值为 10000 毫秒(10 秒);在非池化(单线程)模式下,默认值为 60000 毫秒(60 秒)。
mongoc_uri_set_option_as_int32(uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 5000);
ServerSelectionTimeout
驱动程序在超时之前尝试选择服务器的时间长度。默认值为 30000 毫秒(30 秒)。
mongoc_uri_set_option_as_int32(uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 40000);
套接字检查间隔
仅应用于单线程客户端。如果套接字在这段时间内未被使用,驱动程序会在再次使用之前通过快速“hello”调用来检查连接。默认为 5000 毫秒(5 秒)。
mongoc_uri_set_option_as_int32(uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 10000);
重试选项
注意
智能工作负载管理 (IWM) 中的负载削减
如果带有 SystemOverloadedError 或 RetryableError 标签的错误导致您的应用程序出现故障或出现在您的应用程序日志中,则说明您的集群上可能已启用负载削减 (Load Shedding),并且您的驱动程序可能未升级到支持该功能的版本。我们建议将您的 MongoDB C 驱动程序升级到 2.3 或更高版本。如果您在升级后仍然看到这些错误,可以通过服务器端更改(例如查看您的负载削减配置)或通过应用程序端更改(例如实现自定义错误处理或客户端请求限制)来解决这些错误。根据您的情况,应用程序端更改可能是更可取或必要的。
负载削减 (Load Shedding) 是 IWM 的一项功能,有助于在持续过载期间通过拒绝多余的操作来管理服务器负载。此功能适用于 MongoDB 9.0 及更高版本。
For more information about IWM or handling overload errors, see the Intelligent Workload Management page or Overload Errors page in the Atlas documentation.
其他选项
ApplicationName
作为连接握手的一部分,驱动程序在客户端元数据中传递给服务器的应用名称。建立连接后,服务器会将此值打印到MongoDB日志。该值还会记录在慢速查询日志和配置文件集合中。默认值为空。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?appName=yourAppName");
LoadBalanced
指定驱动程序是否正在连接到负载均衡器。仅当满足以下所有条件时,才能将此属性设立为 true:
您仅指定一个托管名
您没有连接到副本集
您没有使用
SrvMaxHosts属性您没有使用
DirectConnection属性
默认值为 false。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?loadBalanced=true");
SrvMaxHosts
最初填充种子列表或在 SRV 轮询期间向拓扑结构添加新主机时,要随机选择的 SRV 结果的最大数量。默认值为 0。
仅当连接字符串模式设立为 ConnectionStringScheme.MongoDBPlusSrv 时才能使用此属性。连接到副本集时无法使用它。
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?srvMaxHosts=5");
ApplicationName
作为连接握手的一部分,驱动程序在客户端元数据中传递给服务器的应用名称。建立连接后,服务器会将此值打印到MongoDB日志。该值还会记录在慢速查询日志和配置文件集合中。默认值为空。
mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_APPNAME, "yourAppName");
LoadBalanced
指定驱动程序是否正在连接到负载均衡器。仅当满足以下所有条件时,才能将此属性设立为 true:
您仅指定一个托管名
您没有连接到副本集
您没有使用
SrvMaxHosts属性您没有使用
DirectConnection属性
默认值为 false。
mongoc_uri_set_option_as_bool(uri, MONGOC_URI_LOADBALANCED, true);
SrvMaxHosts
最初填充种子列表或在 SRV 轮询期间向拓扑结构添加新主机时,要随机选择的 SRV 结果的最大数量。默认值为 0。
仅当连接字符串模式设立为 ConnectionStringScheme.MongoDBPlusSrv 时才能使用此属性。连接到副本集时无法使用它。
mongoc_uri_set_option_as_int32(uri, MONGOC_URI_SRVMAXHOSTS, 5);
更多信息
有关此页面上使用的类型的更多信息,请参阅以下API文档: