replset的一个目的是保持集群的健壮性,但是,因此需要通过合理的方式连接整个replset,才能在primary宕机的时候,自动启用secondary。
为此,pymongo提供了replica_set_connection来连接整个集群,但是,随着版本的增高,提供该功能的变为mongo_replica_set_client。实例代码如下:
#!/usr/bin/python
#coding:utf-8
import time
from pymongo import MongoReplicaSetClient
conn = MongoReplicaSetClient("192.168.50.100:27017,192.168.50.37:27017,192.168.50.32:27017", replicaset='portscan')
db = conn['test']
cll = db['test']
j =0
while 1:
try:
cll.insert_one({'num':j})
j+=1
print j
print conn.primary
except Exception,e:
print 'err: ',e
#j +=1
#print j
time.sleep(0.5)