mongo replica set维护
1.pymongo小坑
-
pymongo3.0以前,MongoReplicaSetClient是Python连接mongodb副本集的客户端类,跟MongoClient是分开的,MongoClient不能探测副本集的状态变化,比如主节点变化
-
pymongo3.0开始,MongoClient是唯一的client class,不管是单机mongodb,还是副本集,还是shard cluster,都是它一个人负责。
不幸的是,项目里老代码用的旧版pymongo,又没注意MongoReplicaSetClient这个东西,直接用的MongoClient连接副本集。那么当副本集主节点变化时,MongoClient还在继续往原来的主节点写数据,就会报错
2.抢修
最快的方案当然是手动维护mongodb副本集,迫使主节点重回原先主节点mongo命令行连接当前主节点,执行如下命令:cf = rs.conf() cf.members[x].priority = 大于其他节点的整数 # x是你希望接下来成为主节点机器的下标rs.reconfig(cf)若命令执行成功,会触发新的选举,会有一个重连的过程,类似下面信息
2016-04-13T15:13:10.103+0800 DBClientCursor::init call() failed2016-04-13T15:13:10.105+0800 trying reconnect to 10.103.28.94:27037 (10.103.28.94) failed2016-04-13T15:13:10.105+0800 reconnect 10.103.28.94:27037 (10.103.28.94) okreconnected to server after rs command (which is normal)
一般重选,高优先级的node会成为primary.若还是没能成为primary,连接到新的primary, 在新primary上 rs.stepDown().rs.stepDown()可以强制当前primary变为secondary.
3.修正
上面的方案只是应急,不能每次主节点变化后,都来手动切换主节点到指定的节点。
长治久安:使用pymongo3.0或以上版本,mongoengine0.10.6版本开始支持pymongo3.
附一段pymongo官方文档:
Changed in version 3.0:MongoClient
is now the one and only client class for a standalone server, mongos, or replica set.It includes the functionality that had been split intoMongoReplicaSetClient
: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs.