我正在尝试在AWS上使用documentDB集群。在这个集群上,我有2个实例,一个主实例用于写操作,另一个从实例用于读操作…
如果我像这样用connectionString创建连接:
String host = getHost();
Integer port = Integer.parseInt(getPort());
String[] arrCredentials = getCredentials();
String credentials = String.format("%s:%s", arrCredentials[0], arrCredentials[1]);
String database = getDatabase();
String options = "ssl=true&replicaSet=rs0&readPreference=secondaryPreferred";
String connection = String.format("mongodb://%s@%s:%d/%s?%s",
credentials, host, port, database, options);
return MongoClients.create(new ConnectionString(connection));
它工作得很好,readOps由辅助实例提供…
但是,当我尝试这样使用MongoClients.create()
时:
public MongoClient mongoClient() {
return MongoClients.create(MongoClientSettings.builder()
.applyToClusterSettings(settings ->
settings
.hosts(singletonList(new ServerAddress(
getHost(), Integer.parseInt(getPort()))))
.requiredReplicaSetName("rs0")
.requiredClusterType(ClusterType.REPLICA_SET)
)
.applyToSslSettings(setting ->
setting.enabled(true)
)
.readPreference(ReadPreference.secondaryPreferred())
.credential(getCredential())
.build());
}
所有的调用,readOps和writeOps,都由主实例提供。
我找到了!
与ConnectionString
一起创建MongoClienteSettings
时,"ClusterMode
"的值自动设置为"MULTIPLE
"。这不会发生在Builder
…
因此,要获得与MongoClientSetting.Builder()
相同的行为,您需要设置它。这样的:
public MongoClient mongoClient() {
return MongoClients.create(MongoClientSettings.builder()
.applyToClusterSettings(settings ->
settings
.hosts(singletonList(new ServerAddress(
getHost(), Integer.parseInt(getPort()))))
.requiredReplicaSetName("rs0")
.requiredClusterType(ClusterType.REPLICA_SET)
.mode(ClusterConnectionMode.MULTIPLE))
)
.applyToSslSettings(setting ->
setting.enabled(true)
)
.readPreference(ReadPreference.secondaryPreferred())
.credential(getCredential())
.build());
}
现在运行正常了:)
AWS CloudWatch指标