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
# 因此应该考虑先修改参数,再冻结
目录
相关文章
|
JavaScript
vue里怎么使用pdf.js实现pdf文件的预览功能
vue里怎么使用pdf.js实现pdf文件的预览功能
1380 0
vue里怎么使用pdf.js实现pdf文件的预览功能
|
SQL 运维 JavaScript
Yearning目前最流行的开源数据库审核平台
Yearning帮你减小日常变更数据库的风险,规范有序记录进行数据库变更操作
2129 0
Yearning目前最流行的开源数据库审核平台
|
SQL 存储 关系型数据库
|
消息中间件 数据采集 存储
Kafka常见问题总结
会不会丢消息? Offset 怎么保存? Consumer 重复消费问题怎么处理? 如何保证消息的顺序? 数据倾斜怎么处理? 一个 Topic 分配多少个 Partiton 合适以及修改 Partiton有哪些限制?
|
12月前
|
数据安全/隐私保护
图片添加文字水印
【10月更文挑战第21天】图片添加文字水印是一种重要的保护和宣传手段。通过合理选择文字内容、设计和添加方法,可以有效地为图片添加水印,保护图片的权益和价值。同时,随着技术的发展,我们也需要不断探索和创新,以适应不断变化的需求。你还可以根据具体的行业需求和实际情况,进一步深入研究和优化文字水印的添加策略,确保图片得到更好的保护和利用。
328 0
|
12月前
|
机器学习/深度学习 数据采集 人工智能
CDGA|推动数据治理与传统产业深度融合:策略与实践路径
持续改进与优化:建立数据治理的持续改进机制,定期评估数据治理效果,总结经验教训,不断优化数据治理策略与实践路径。
|
SQL JSON 关系型数据库
SqlAlchemy 2.0 中文文档(七十五)(1)
SqlAlchemy 2.0 中文文档(七十五)
246 4
|
存储 人工智能 弹性计算
自动化搭建专属 AI 绘图服务
本文介绍了如何使用通义万相AIGC技术和阿里云的计算和存储产品来搭建自己的AI绘画服务。首先,通过创建基础云产品资源和部署AI绘画服务的步骤来开始搭建服务。然后,介绍了模板的原理和内容,以及ROS编排引擎的作用。接下来,详细介绍了AI绘画服务的一键部署过程,包括定义参数、模板的编写和ROS的使用。最后,提到了应用运行环境的搭建和自定义应用页面的方法。通过ROS的自动化部署,用户可以方便快捷地拥有自己的AI绘画服务。
|
Oracle 关系型数据库 MySQL
MySQL 8.0中没FRM文件
MySQL 8.0中没FRM文件
127 1
|
弹性计算 安全 关系型数据库
rds安全组规则
云数据库RDS的安全组规则是虚拟防火墙,用于控制网络访问权限,确保数据库安全。配置要点包括:指定RDS实例的安全组,设定入方向规则(如源IP、协议和端口),考虑默认规则的开放程度。根据场景,同组内外的ECS实例需不同配置。管理员应合理规划规则,确保业务需求与安全性平衡,并定期审计更新。
324 3