How do I confirm I am reading the data from Mongo secondary server from Java

295 views Asked by At

For performance optimisation we are trying to read data from Mongo secondary server for selected scenarios. I am using the inline query using "withReadPreference(ReadPreference.secondaryPreferred())" to read the data, PFB the code snippet.

What I want to confirm the data we are getting is coming from secondary server after executing the inline query highlighted, is there any method available to check the same from Java or Springboot

public User read(final String userId) { final ObjectId objectId = new ObjectId(userId);

    final User user = collection.withReadPreference(ReadPreference.secondaryPreferred()).findOne(objectId).as(User.class);
    
    
    
    return user;
}
1

There are 1 answers

3
Buzz Moschetti On

Pretty much the same way in Java. Note we use secondary() not secondaryPrefered(); this guarantees reads from secondary ONLY:

import com.mongodb.ReadPreference;

{
    // This is your "regular" primaryPrefered collection:
    MongoCollection<BsonDocument> tcoll = db.getCollection("myCollection", BsonDocument.class);
    //  ... various operations on tcoll, then create a new
    //  handle that FORCES reads from secondary and will timeout and
    //  fail if no secondary can be found:
    MongoCollection<BsonDocument> xcoll = tcoll.withReadPreference(ReadPreference.secondary());

    BsonDocument f7 = xcoll.find(queryExpr).first();
}