在本指南中,您可以学习;了解Go驾驶员如何管理集群以及如何自定义集群设置。
在创建新的 Client实例时,您可以使用连接字符串或 ClientOptions 结构为集群指定设置。 选择 Connection String 或 ClientOptions标签页,查看可用选项。
Client
ClientOptions
下表描述了可在连接字符串中使用的参数,这些参数用于在与MongoDB 集群交互时修改驱动程序的行为:
serverSelectionTimeoutMS
指定驾驶员在抛出错误之前等待服务器可用的最长时间。
默认值:30 秒
localThresholdMS
指定选择服务器的最大延迟(以毫秒为单位)。
默认值:15 毫秒
replicaSet
指定要连接到的副本集的名称。
directConnection
指定是否绕过副本集或分片集群,直接连接到单个服务器。
默认: false
false
loadBalanced
指定驾驶员是否使用负载负载均衡器连接到MongoDB 。如果设立为 true,则驾驶员假定其通过负载负载均衡器进行连接。
true
只有在满足以下要求时,您才能将此选项设置为 true:
仅指定一个托管名
您没有连接到副本集
srvMaxHosts 选项未设置或其值为 0
srvMaxHosts
0
directConnection 选项未设置或其值为 false
srvServiceName
Specifies the service name of the SRV resource records the driver retrieves to construct your seed list. You must use the DNS Seed List Connection Format in your connection string to use this option.
下表描述了可以链接到 ClientOptions 结构以修改驱动程序行为的几种方法:
SetServerSelectionTimeout()
SetLocalThreshold()
SetReplicaSet()
SetDirect()
SetLoadBalanced()
SetSRVServiceName()
Specifies a custom service name of the SRV resource records the driver retrieves to construct your seed list. To use a custom SRV service name in SRV discovery, you must call this function before you call ApplyURI().
ApplyURI()
要学习;了解有关可用方法的更多信息,请参阅API文档部分。
选择 Connection String 或 ClientOptions标签页,查看相应示例:
以下代码使用连接字符串将最大服务器选择超时配置为 10 秒,并将本地阈值配置为 20 毫秒:
const uri = "mongodb://localhost:27017/?serverSelectionTimeoutMS=10000&localThresholdMS=20"
以下代码创建一个客户端并将连接字符串传递给 ApplyURI() 方法:
client, err := mongo.Connect(options.Client().ApplyURI(uri))if err != nil { log.Fatal(err)}
以下代码创建一个客户端,并设置集群选项,其中最大服务器选择超时为 10 秒,本地阈值为 20 毫秒:
clientOptions := options.Client(). ApplyURI(uri). SetServerSelectionTimeout(10 * time.Second). SetLocalThreshold(20 * time.Millisecond)client, err := mongo.Connect(clientOptions)if err != nil { log.Fatal(err)}
要学习;了解有关本指南中方法和类型的更多信息,请参阅以下API文档:
客户
后退
压缩网络流量
来年
Stable API
在此页面上