我正在尝试使用PyMongo连接到MongoDB复制集,并手动平衡读取负载与ReadPreference
。
问题在于,无论我尝试使用MongoClient
,它总是从PRIMARY
读取。
我在Linux Mint 17.2上使用Python 2.7.6和PyMongo 2.6.3以及mongodb-10gen
2.4.14(所有遗留原因)。
我的连接序列看起来像这样(没有打印,并且对连接中某些数据库的某些集合提出了大量请求):
>>> from pymongo import MongoClient, ReadPreference
>>> HOST = "10.0.0.51"
>>> PORT = 49029
>>> print MongoClient(host=HOST, port=PORT, replicaset="rs02", readPreference=ReadPreference.SECONDARY)
MongoClient([u'XXXX-MNGO03664:49029', u'XXXX-MNGO03663:49029'])
这是使用PyMongo的正确方法> 3,从我所读到的。不幸的是我坚持使用PyMongo 2.6.3,我只能假设这就是为什么它不能从二级读取。
经过一番挖掘后,我发现ReplicaSetConnection
(自PyMongo 2.4以来已弃用)和MongoReplicaSetClient
(参见例如pymongo replication secondary readreference not work和pymongo: Advantage of using MongoReplicaSetClient?),但它也没有找到这似乎对我有用,但出于不同的原因。
>>> print MongoReplicaSetClient(host=HOST, port=PORT, replicaset="rs02", readPreference=ReadPreference.SECONDARY)
MongoReplicaSetClient([])
客户似乎无法看到replicaset的成员...... 当然,当我开始阅读这个连接时,它不起作用。
>>> myConn = MongoReplicaSetClient(host=HOST, port=PORT, replicaset="rs02", readPreference=ReadPreference.SECONDARY)
>>> print myConn.someDB.someCollection.count()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 759, in count
return self.find().count()
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 640, in count
**command)
File "/usr/local/lib/python2.7/dist-packages/pymongo/database.py", line 391, in command
result = self["$cmd"].find_one(command, **extra_opts)
File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 604, in find_one
for result in self.find(spec_or_id, *args, **kwargs).limit(-1):
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 904, in next
if len(self.__data) or self._refresh():
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 848, in _refresh
self.__uuid_subtype))
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 782, in __send_message
res = client._send_message_with_response(message, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_replica_set_client.py", line 1631, in _send_message_with_response
raise AutoReconnect(msg, errors)
pymongo.errors.AutoReconnect: No replica set secondary available for query with ReadPreference SECONDARY
请注意,当我尝试使用ReadPreference.PRIMARY
阅读时会出现相同的错误。
这里奇怪的是,如果我更改要连接的replicaset的名称,客户端会发现它不存在:
>>> print MongoReplicaSetClient(host=HOST, port=PORT, replicaset="rs42", readPreference=ReadPreference.SECONDARY)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_replica_set_client.py", line 742, in __init__
self.refresh()
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_replica_set_client.py", line 1135, in refresh
% (host, port, self.__name))
pymongo.errors.ConfigurationError: 10.0.0.51:49029 is not a member of replica set rs42
所以我假设在正常情况下,它有一种方法可以看到这里有一个复制品,谁是它的成员。