billtian
billtian

Reputation: 6831

reading data from specific nodes in mongo replica set

I have a replica set of three members. Is it possible that I just want to read from one of the two secondary nodes? I use following code where the ip is one of the secondary, but I still saw the traffic was deployed to other nodes.

Mongo mongo = new MongoClient("171.21.43.34");

Upvotes: 3

Views: 1708

Answers (1)

billtian
billtian

Reputation: 6831

The best way is to use tags as stated in mongodb manual.

https://docs.mongodb.com/manual/tutorial/configure-replica-set-tag-sets/

conf = rs.conf()
conf.members[0].tags = { "offline": "false"}
conf.members[1].tags = { "offline": "false"}
conf.members[2].tags = { "offline": "true"}
rs.reconfig(conf)

In the client, you just set the readpreference to that tag

    MongoClientOptions options = MongoClientOptions
                    .builder()
                    .connectionsPerHost(config.connectionLimit)
                    .readPreference(TaggableReadPreference.secondaryPreferred(new TagSet(new Tag("offline", "true"))))
                    .socketTimeout(config.socketTimeout)
                    .connectTimeout(config.connectionTimeout)
                    .build();
    mongo = new MongoClient(NewsDAOConfig.parseAddresses(config.mongoAddress), options);

Upvotes: 5

Related Questions