I'm trying to use a cluster of documentDB on AWS. On this cluster, I have 2 instances, one primary for writeOps and one secondary for readOps...
If I create the connection with connectionString like this:
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));
It works well, and the readOps are served by the secondary instance...
But, when I try to use MongoClients.create()
this way:
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());
}
All calls, readOps and writeOps, are served by the primary instance.
I found it!!!
When you create the MongoClienteSettings
with ConnectionString
, the value of ClusterMode
is automaticly setted to MULTIPLE
. That doesn't occur with Builder
...
So, to get the same behavour with MongoClientSetting.Builder()
, you need to set it. Like this:
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());
}
Now it's working well :)