0

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;
}
Dinesh
  • 11
  • 1

1 Answers1

0

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();
}
Buzz Moschetti
  • 7,057
  • 3
  • 23
  • 33
  • Thanks for the responseI aggree withtimeout and fail if no secondary can be found . How I can ensure the data is read from Secondary server. Is there any method available to get the server / host name. I have tried with below piece of code but it is giving null pointer for me. – Dinesh Dec 14 '21 at 08:16
  • collection.withReadPreference(ReadPreference.secondaryPreferred()).getDBCollection().find().getServerAddress().getHost(); – Dinesh Dec 14 '21 at 08:18
  • You get data from the secondary only when the read preference is `Secondary`. What other assurance do you need? Also note that in multinode rep set, there could be several secondaries and there is no guarantee of which one will be hit. – Buzz Moschetti Dec 14 '21 at 16:08