python 获得复制通过pyMongo延迟Mongo

emeijp43  于 2023-01-19  发布在  Python
关注(0)|答案(1)|浏览(89)

我正在尝试使用db.rs.printSlaveReplicationInfo从python获得replication-delay,但是没有找到合适的方法。我尝试了下面的方法,但是没有帮助。

>>>from pymongo import MongoClient
>>>client = MongoClient()
>>>db = client.test_database
>>>db.rs.printSlaveReplicationInfo                 
Collection(Database(MongoClient([u'10.0.0.19:10006', u'10.0.0.68:10002']), u'xyz'), u'rs.printSlaveReplicationInfo')
db.rs.printSlaveReplicationInfo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib64/python2.7/site-packages/pymongo/collection.py", line 2413, in __call__
    self.__name.split(".")[-1])
TypeError: 'Collection' object is not callable. If you meant to call the 'printSlaveReplicationInfo' method on a 'Collection' object it is failing because no such method exists.
>>> db.rs                            
Collection(Database(MongoClient([u'10.0.0.19:10006', u'10.0.0.68:10002']), u'xyz'), u'rs')

有人能帮上忙吗?或者怎么做?
先谢了。

mrphzbgm

mrphzbgm1#

我找到了答案。下面是完整的代码:
(Note:您需要具有管理员权限才能运行此命令。)

uri = "mongodb://usernamen:password@host:port/admin"
conn = pymongo.MongoClient(uri)
db = conn['admin']
db_stats = db.command({'replSetGetStatus'  :1})

primary_optime = 0
secondary_optime = 0

for key in db_stats['members'] : 
    if key['stateStr'] == 'SECONDARY' :
        secondary_optime = key['optimeDate']
    if key['stateStr'] == 'PRIMARY' : 
        primary_optime =key['optimeDate']

print 'primary_optime : ' + str(primary_optime)
print 'secondary_optime : ' + str(secondary_optime)

seconds_lag = (primary_optime - secondary_optime ).total_seconds()
#total_seconds() userd to get the lag in seconds rather than datetime object
print 'secondary_lag : ' + str(seconds_lag)

optime重复mongo节点拥有数据的日期。
您可以在这里阅读更多信息:
https://docs.mongodb.com/manual/reference/command/replSetGetStatus/

相关问题