Mongodb Read preferences

老子叫甜甜 提交于 2019-12-08 04:24:24

问题


SETUP:

I have one PRIMARY and two SECONDARY instances of mongodb. One of the two secondary instances is hosted in the same region as my web app.

I am using pymongo for connecting.

QUERY:

How can I get connection to a SECONDARY with lower latency.

Currently I am doing this:

  from pymongo import ReplicaSetConnection
  from pymongo import ReadPreference

  db = ReplicaSetConnection('localhost:27017', replicaSet='rs1')['my_db']
  db.read_preference = ReadPreference.SECONDARY

I get a connection to any one of the SECONDARY. How can I force to get connection from the instance with lower latency

Thanks!!


回答1:


The read preferences are as follows:

  • PRIMARY: Queries are sent to the primary of the replica set.
  • PRIMARY_PREFERRED: Queries are sent to the primary if available, otherwise a secondary.
  • SECONDARY: Queries are distributed among secondaries. An error is raised if no secondaries are available.
  • SECONDARY_PREFERRED: Queries are distributed among secondaries, or the primary if no secondary is available.
  • NEAREST: Queries are distributed among all members.

So theres no specific one for the nearest secondary. You could achieve this by combining NEAREST and tag_sets and tagging the secondaries.

Then if the secondaries have been tagged {'secondaries': 1} you can read from the nearest secondary like so:

from pymongo import ReplicaSetConnection
from pymongo import ReadPreference

db = ReplicaSetConnection('localhost:27017', replicaSet='rs1')['my_db']
db.read_preference = ReadPreference.NEAREST
db.tag_sets = [{'secondaries': 1}]

Update:

You should note that if an election occurs and the topology of your replicaset changes then you'd have to manually change the tag_sets to represent the new secondaries.




回答2:


This answer is very specific to my situation, because my nearest secondary is in the same region as my web server (as good as running on the same machine), so the data transfer would be insanely fast, plus I don't have to pay for bandwidth usage (which over the month might become significant considering the amount of data).

Otherwise the default value for 'secondary_acceptable_latency_ms' = 15ms. So it doesn't really matter.

So in case someone finds himself/herself in the same situation, this is what to do:

    from pymongo import ReplicaSetConnection
    from pymongo import ReadPreference

    db = ReplicaSetConnection('localhost:27017', replicaSet='rs1')['my_db']
    db.read_preference = ReadPreference.SECONDARY
    db.secondary_acceptable_latency_ms = 0.001

Thanks!!



来源:https://stackoverflow.com/questions/13529174/mongodb-read-preferences

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