3

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");
billtian
  • 6,589
  • 4
  • 18
  • 28
  • 1
    Indeed you can read from secondaries. All you have to specify your intention in connection string. see https://docs.mongodb.org/manual/core/read-preference/. You can always read directly from any node. – Saleem Mar 30 '16 at 00:42
  • Unless you set a read preference even specifying an address of a "secondary' ( which you should not really do ) does not mean that is the **only** node connected. Since this is a replicaset, the driver will "self discover" all member nodes anyway. So read preference is the "king" here. Also if your members are not "balanced" ( ie one is a more capable server than the other ) this can again be a very bad thing, since you will end up with a "lag" on the slower node that might actually lead to falling behind the oplog. – Blakes Seven Mar 30 '16 at 00:47
  • Yes, I second @BlakesSeven. You shouldn't be reading directly from specific secondary in replicaset unless you have special needs. e.g. designating a specific secondary as reporting server or so. – Saleem Mar 30 '16 at 00:53

1 Answers1

5

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);
billtian
  • 6,589
  • 4
  • 18
  • 28