Replica Set可以被称为副本集。其作用或者说好处有很多,最起码的比如可以做数据备份,读写分离等。副本集在mongo中的表现如下图所示:
从这里我们可以看到很多内容:每一个成员的身份,状态都已经很清楚的描述出来了。
那么我如何配置这样一个副本集呢?接下来步骤来了。
1) 副本集配置
var config = {
"_id" : "shard1",
"members" : [
{
"_id" : 0,
"host" : "hostA:27017",
"priority" : 2
},
{
"_id" : 2,
"host" : "hostB:27019",
"arbiterOnly" : true //投票,不存储数据
},
{
"_id" : 3,
"host" : "hostC:9200",
"priority" : 10 //priority 越高则投票权重越高
}
]
}
2) 使配置生效
rs.initiate(config)
不过这样其实是不会真的起作用的,因为在启动各个mongo实例的时候还需要按照要求来。下面给出一个配置的实例,这句话意思为你需要指定mongo以一个副本集的方式启动。
numactl --interleave=all ./mongod --replSet shard1 --port 27017 --dbpath ../data/shard12/ --logpath ../log/shard12.log --logappend --fork
那如果我在一个现有的副本集中想要添加或者删除一个成员,该怎么操作呢?
使用rs.add("hostD:port")
其实,如果我已经成功配置好一个副本集或者我以副本集的方式启动了一个实例,那么,我可以使用命令rs.help()
看到可用的命令
rs.status() //{ replSetGetStatus : 1 } checks repl set status
rs.initiate() // { replSetInitiate : null } initiates set with default settings
rs.initiate(cfg) // { replSetInitiate : cfg } initiates set with configuration cfg
rs.conf() // get the current configuration object from local.system.replset
rs.reconfig(cfg) // updates the configuration of a running replica set with cfg (disconnects)
rs.add(hostportstr) // add a new member to the set with default attributes (disconnects)
rs.add(membercfgobj) // add a new member to the set with extra attributes (disconnects)
rs.addArb(hostportstr) // add a new member which is arbiterOnly:true (disconnects)
rs.stepDown([secs]) // step down as primary (momentarily) (disconnects)
rs.syncFrom(hostportstr) // make a secondary to sync from the given member
rs.freeze(secs) // make a node ineligible to become primary for the time specified
rs.remove(hostportstr) // remove a host from the replica set (disconnects)
rs.slaveOk() // shorthand for db.getMongo().setSlaveOk()
rs.printReplicationInfo() // check oplog size and time range
rs.printSlaveReplicationInfo() // check replica set members and replication lag
db.isMaster() // check who is primary
有了这个之后,相信大家就可以在应用中自由发挥了,基本上对副本集的各种操作都已经包含了。最关键的是要理解配置和命令的意思。我曾经在工作中遇到一个问题,就是把现在身份为primary的实例替换为另一个规定好的实例,并且让这个新实例为primary,当时因为对这些操作和配置不熟,导致走了些弯路。
1)rs.add('new instance')
2 ) var config = rs.conf()
3) config.members[4].priority=100
4) rs.reconfig(config)
4) rs.stepDown()
5) rs.remove('old primary instance')