質問

I have configured my replica set with tag fields as given in doc example:

{
    "_id" : "rs0",
    "version" : 2,
    "members" : [
             {
                     "_id" : 0,
                     "host" : "mongodb0.example.net:27017",
                     "tags" : {
                             "dc": "east",
                             "use": "production"
                     }
             },
             {
                     "_id" : 1,
                     "host" : "mongodb1.example.net:27017",
                     "tags" : {
                             "dc": "east",
                             "use": "reporting"
                     }
             },
             {
                     "_id" : 2,
                     "host" : "mongodb2.example.net:27017",
                     "tags" : {
                             "use": "production"
                     }
             }
     ]
}

Now my question is if I send read queries with read concern like "nearest","primarypreferred" will it be able to pick this tags automaticaly, or i should pass the "dc" name along with my find query.If anyone can help me regarding the same.

役に立ちましたか?

解決

If you want to set tags with your read preference (whatever it is except primary), you have to set it manually, something such as:

DBCollection collection = ...    

ReadPreference dcReadPref =
     ReadPreference.nearest(new BasicDBObject("dc", "east"));

collection.findOne(new BasicDBObject("field", "value"), null, dcReadPref);

Unfortunately, the find() method doesn't have a variance including ReadPreference as argument (at least couldn't find such in javadoc) . You will have to do something like this:

DBCollection collection = ...
ReadPreference defaultReadPref = collection.getReadPreference();
collection.setReadPreference(dcReadPref);
...
collection.find(new BasicDBObject("field", "value"));
...
collection.setReadPreference(defaultReadPref); // when done restore default

You can set read preference (w/wo tags) at driver, database, collection or operation level.

To also include your environment in tags set:

String env = ... / get it from somewhere

DBObject dcTag = new BasicDBObject("dc", "east"):
DBObject envTag = new BasicDBObject("use", env);

ReadPreference pref = ReadPreference.primaryPreferred(dcTag, envTag);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top