mongoDB replica set configuration

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介:
startup mongodb with --replSet command option
example : 
1. startup one node:
mongod --replSet setname[/rmt_ip:$port]
2. startup another node :
mongod --replSet setname[/rmt_ip:$port]
3. run ininiate command within one of the nodes only : 
db.runCommand({replSetInitiate : <config_object>}) or
rs.initiate(<config_object>)
如果不带参数rs.initiate(),初始化包含setname[/rmt_ip:$port]的节点.

<config_object>完整格式:
{
  _id : <setname>,
  members: [
    {
      _id : <ordinal>,
      host : <hostname[:port]>,
      [, priority: <priority>]
      [, arbiterOnly : true]
      [, votes : <n>]
      [, hidden : true]
      [, slaveDelay : <n>]
      [, buildIndexes : <bool>]
      [, initialSync : {
           [state : 1|2,]
           [_id : <n>,]
           [name : <host>,]
           [optime : <date>]}]
    }
    , ...
  ],

  [settings: {
    [getLastErrorDefaults: <lasterrdefaults>]
    [, heartbeatSleep : <seconds>]
    [, heartbeatTimeout : <seconds>]
    [, heartbeatConnRetries : <n>]
  }]
}
参数说明:
强制参数:

    _id - the set name. This must match command line setting. Set names are usually alphanumeric and, in particular, cannot contain the '/' character.
    members - an array of servers in the set. For simpler configs, one can often simply set _id and host fields only – all the rest are optional.
          _id - each member has an _id ordinal, typically beginning with zero and numbered in increasing order. when a node is retired (removed from the config), its _id should not be reused.
          host - host name and optionally the port for the member

Member可选参数:

    arbiterOnly - if true, this member will participate in consensus (voting) but receive no data. Defaults to false.
    votes - number of votes this member gets in elections. Defaults to 1. Normally you do not need to set this parameter. Sometimes useful when the number of nodes are even or for biasing towards a particular data center.
    priority - priority a server has for potential election as primary. The highest priority member which is up will become primary. Default 1.0. Priority zero means server can never be primary (0 and 1 are the only priorities currently supported).
    hidden - when true, do not advertise the member's existence to clients in isMaster command responses. (v1.7+)
    slaveDelay - how far behind this slave's replication should be (in seconds). Defaults to 0 (as up-to-date as possible). Can be used to recover from human errors (accidentally dropping a database, etc.). This option can only be set on passive members. (v1.6.3+)
    buildIndexes - boolean, defaults to true. If the priority is 0, you can set buildIndexes to false to prevent indexes from being created on this member. This could be useful on a machine which is only used for backup as there is less overhead on writes if there are no secondary indexes. Note: the _id index is always created.
    initialSync (1.7.4+) - allows you to specify where this server should initially sync from. If not specified, the server will choose the first primary or secondary it finds that is healthy. The default should usually work fine, but you can change this by specifying any of the following options:
          state : 1 forces the server to clone from the primary, 2 from a secondary.
          _id : the _id of the member to clone from.
          name : the host to clone from.
          optime : finds a server that is at least this up-to-date to clone from. Can be a Date or Timestamp type.

Set可选参数:

The final optional argument, settings, can be used to set options on the set as a whole. Often one can leave out settings completely from the config as the defaults are reasonable.

    getLastErrorDefaults specifies defaults for the getlasterror command. If the client calls getLastError with no parameters, the default object specified here is used. (v1.6.2+)
    heartbeatSleep how frequently nodes should send a heartbeat to each other (default: 2 seconds, must be greater than 10 milliseconds).
    heartbeatTimeout indicates how long a node needs to fail to send data before we note a problem (default: 10 seconds, must be greater than 10 milliseconds).
    heartbeatConnRetries is how many times after heartbeatTimeout to try connecting again and getting a new heartbeat (default: 3 tries).


mongo shell replica set reference commands : 
reptest:PRIMARY> 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.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()

        db.isMaster()                   check who is primary

        reconfiguration helpers disconnect from the database so the shell will display
        an error, even if the command succeeds.
        see also http://<mongod_host>:28017/_replSet for additional diagnostic info

或者使用命令:
db.runCommand({})
    * { isMaster : 1 }
    * { replSetGetStatus : 1 }
    * { replSetInitiate : <config> }
    * { replSetReconfig: <config> }
    * { replSetStepDown : <seconds> }
    * { replSetFreeze : <seconds> }

例如:
reptest:PRIMARY> db.runCommand({"replSetGetStatus" : 1})
{
        "set" : "reptest",
        "date" : ISODate("2011-01-12T02:38:30Z"),
        "myState" : 1,
        "members" : [
                {
                        "_id" : 0,
                        "name" : "172.16.3.33:5281",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 6595,
                        "optime" : {
                                "t" : 1294655286000,
                                "i" : 1
                        },
                        "optimeDate" : ISODate("2011-01-10T10:28:06Z"),
                        "lastHeartbeat" : ISODate("2011-01-12T02:38:30Z")
                },
                {
                        "_id" : 1,
                        "name" : "db-172-16-3-39.sky-mobi.com.hz.gs:5281",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "optime" : {
                                "t" : 1294655286000,
                                "i" : 1
                        },
                        "optimeDate" : ISODate("2011-01-10T10:28:06Z"),
                        "self" : true
                }
        ],
        "ok" : 1
}

The myState field indicates the state of this server. Valid states are:
0     Starting up, phase 1
1     Primary
2     Secondary
3     Recovering
4     Fatal error
5     Starting up, phase 2
6     Unknown state
7     Arbiter
8     Down

The health field indicates the health of this server. Valid states are:
0     Server is down
1     Server is up

The errmsg field can contain informational messages, as shown above.

force a node to be primary at a given point in time,use below method : 
{ replSetStepDown : <seconds> }
Manually tell a member to step down as primary. Node will become eligible to be primary again after the specified number of seconds. (Presumably, another node will take over by then if it were eligible.)

{ replSetFreeze : <seconds> }
'Freeze' state of this member to the extent we can do that. What this really means is that this node will not attempt to become primary until the time period specified expires.
You can call again with {replSetFreeze:0} to unfreeze sooner. A process restart unfreezes the member also.
If the node is already primary, you need to use replSetStepdown instead.

# 修改replica set配置
> // shell v1.7.x:
> // example : give 1st set member 2 votes
> cfg = rs.conf()
> cfg.members[0].votes = 2
> rs.reconfig(cfg)

# 修改配置需要注意 
    * You must connect to the current primary.
    * A majority of members of the set must be up.

# 如两节点的replica环境如果将主节点冻结,在新的主节点修改配置后保存的时候可能会报错,原因是老的主节点未解冻.不能接收到消息.
如下:
reptest:PRIMARY> rs.reconfig(cfg)
Wed Jan 12 11:02:31 query failed : admin.$cmd { replSetReconfig: { _id: "reptest", version: 9, members: [ { _id: 0, host: "172.16.3.33:5281", votes: 2 }, { _id: 1, host: "172.16.3.39:5281", votes: 2.0 } ] } } to: 127.0.0.1:5281
shell got exception during reconfig: Error: error doing query: failed
in some circumstances, the primary steps down and closes connections on a reconfig
null
Wed Jan 12 11:02:31 trying reconnect to 127.0.0.1:5281
Wed Jan 12 11:02:31 reconnect 127.0.0.1:5281 ok
# 因此应该考虑先修改参数,再冻结
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
打赏
0
0
0
0
20694
分享
相关文章
在K8S中,Replica Set和Replication Controller之间有什么区别?
在K8S中,Replica Set和Replication Controller之间有什么区别?
If you are using the git profile, you need to set a Git URI in your configuration. If you are using
If you are using the git profile, you need to set a Git URI in your configuration. If you are using
291 0
mongodb搭建Replica Set
mongodb搭建Replica Set 简单高效
263 0
No valid Maven installation found. Either set the home directory in the configuration dialog or set
No valid Maven installation found. Either set the home directory in the configuration dialog or set
1275 0
No valid Maven installation found. Either set the home directory in the configuration dialog or set
MongoDB系列-解决面试中可能遇到的MongoDB复制集(replica set)问题
MongoDB复制集(replica set):MongoDB复制集维护相同数据集的一组mongod进程,复制集是生产部署的基础,具有数据冗余以及高可用性。
446 0
MongoDB系列-解决面试中可能遇到的MongoDB复制集(replica set)问题
MongoDB系列-复制集(Replica Set)应用部署(生产、测试、开发环境)
通过在不同的计算机上托管mongod实例来尽可能多地保持成员之间的分离。将虚拟机用于生产部署时,应将每个mongod实例放置在由冗余电源电路和冗余网络路径提供服务的单独主机服务器上,而且尽可能的将副本集的每个成员部署到自己的计算机绑定到标准的MongoDB端口27017。
663 0
基于docker容器下mongodb 4.0.0 的Replica Sets+Sharded Cluster集群(3)
基于docker容器下mongodb 4.0.0 的Replica Sets+Sharded Cluster集群(3)
197 0
【c++丨STL】基于红黑树模拟实现set和map(附源码)
本文基于红黑树的实现,模拟了STL中的`set`和`map`容器。通过封装同一棵红黑树并进行适配修改,实现了两种容器的功能。主要步骤包括:1) 修改红黑树节点结构以支持不同数据类型;2) 使用仿函数适配键值比较逻辑;3) 实现双向迭代器支持遍历操作;4) 封装`insert`、`find`等接口,并为`map`实现`operator[]`。最终,通过测试代码验证了功能的正确性。此实现减少了代码冗余,展示了模板与仿函数的强大灵活性。
57 2
哈希表模拟封装unordered_map和unordered_set
哈希表模拟封装unordered_map和unordered_set