mongoDB replica set configuration

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介:
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
相关文章
|
10月前
|
存储 NoSQL MongoDB
mongodb搭建Replica Set
mongodb搭建Replica Set 简单高效
163 0
|
Java Maven
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
455 0
No valid Maven installation found. Either set the home directory in the configuration dialog or set
|
存储 NoSQL 测试技术
MongoDB系列-解决面试中可能遇到的MongoDB复制集(replica set)问题
MongoDB复制集(replica set):MongoDB复制集维护相同数据集的一组mongod进程,复制集是生产部署的基础,具有数据冗余以及高可用性。
310 0
MongoDB系列-解决面试中可能遇到的MongoDB复制集(replica set)问题
|
存储 NoSQL 网络协议
MongoDB系列-复制集(Replica Set)应用部署(生产、测试、开发环境)
通过在不同的计算机上托管mongod实例来尽可能多地保持成员之间的分离。将虚拟机用于生产部署时,应将每个mongod实例放置在由冗余电源电路和冗余网络路径提供服务的单独主机服务器上,而且尽可能的将副本集的每个成员部署到自己的计算机绑定到标准的MongoDB端口27017。
431 0
|
NoSQL Java MongoDB
基于docker容器下mongodb 4.0.0 的Replica Sets+Sharded Cluster集群(3)
基于docker容器下mongodb 4.0.0 的Replica Sets+Sharded Cluster集群(3)
160 0
|
NoSQL MongoDB Docker
基于docker容器下mongodb 4.0.0 的Replica Sets+Sharded Cluster集群(2)
基于docker容器下mongodb 4.0.0 的Replica Sets+Sharded Cluster集群(2)
168 0
|
NoSQL MongoDB Docker
基于docker容器下mongodb 4.0.0 的Replica Sets+Sharded Cluster集群(1)
基于docker容器下mongodb 4.0.0 的Replica Sets+Sharded Cluster集群(1)
146 0
基于docker容器下mongodb 4.0.0 的Replica Sets+Sharded Cluster集群(1)
|
存储 NoSQL Shell
(1)解锁MongoDB replica set核心姿势
本文倒腾目前大热的MongoDB Replica Set集群,在倒腾的同时串讲一些 MongoDB特性。
(1)解锁MongoDB replica set核心姿势
|
13天前
|
NoSQL MongoDB 数据库
MongoDB数据恢复—MongoDB数据库文件被破坏的数据恢复案例
服务器数据恢复环境: 一台Windows Server操作系统服务器,服务器上部署MongoDB数据库。 MongoDB数据库故障&检测: 工作人员在未关闭MongoDB数据库服务的情况下,将数据库文件拷贝到其他分区。拷贝完成后将原MongoDB数据库所在分区进行了格式化操作,然后将数据库文件拷回原分区,重新启动MongoDB服务,服务无法启动。
|
17天前
|
NoSQL MongoDB Redis
Python与NoSQL数据库(MongoDB、Redis等)面试问答
【4月更文挑战第16天】本文探讨了Python与NoSQL数据库(如MongoDB、Redis)在面试中的常见问题,包括连接与操作数据库、错误处理、高级特性和缓存策略。重点介绍了使用`pymongo`和`redis`库进行CRUD操作、异常捕获以及数据一致性管理。通过理解这些问题、易错点及避免策略,并结合代码示例,开发者能在面试中展现其技术实力和实践经验。
148 8
Python与NoSQL数据库(MongoDB、Redis等)面试问答