reading data from specific nodes in mongo replica set

你。 提交于 2020-01-02 15:03:46

问题


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");

回答1:


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);


来源:https://stackoverflow.com/questions/36297633/reading-data-from-specific-nodes-in-mongo-replica-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!