MongoClient 不从辅助服务器读取

MongoClient doesn't read from secondary server

我正在尝试在 AWS 上使用 documentDB 集群。 在这个集群上,我有 2 个实例,一个主实例用于 writeOps,一个辅助实例用于 readOps...

如果我像这样使用 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 的值会自动设置为 MULTIPLEBuilder...

不会发生这种情况

因此,要获得与 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 Metrics