翻译或纠错本页面

禁止从节点升职为主节点

概述

在复制集的默认设置下。 secondary 是有机会在选举中升职为主节点的。我们可以调节 priority 来使得某个节点成为主节点的可能性更高或者更低又或是禁止其成为主节点。

不能成为主节点的从节点也不会触发选举。在其他方面与其他从节点无区别。

我们可以将 secondary 的优先级设置为 0 来阻止其在选举中升职为 primary 。 关于这样的设定的意义请参见 优先级为0的复制集成员

注意事项

When updating the replica configuration object, access the replica set members in the members array with the array index. The array index begins with 0. Do not confuse this index value with the value of the members[n]._id field in each document in the members array.

注解

MongoDB不能将现在的 primary 的优先级设置为 0 。为了防止现有的主节点再次成为主节点,我们需要先使用 rs.stepDown() 来将主节点降职。

步骤

本文使用了由5个节点组成的复制集为例。

警告

  • The rs.reconfig() shell method can force the current primary to step down, which causes an election. When the primary steps down, the mongod closes all client connections. While this typically takes 10-20 seconds, try to make these changes during scheduled maintenance periods.
  • 为了能让复制集的配置修改成功应用,我们需要确保复制集的多数节点是可用的。如果我们的复制集是由偶数个节点组成的,那就需要新增一个 arbiter 来确保选举的正常进行。

1

Retrieve the current replica set configuration.

The rs.conf() method returns a replica set configuration document that contains the current configuration for a replica set.

In a mongo shell connected to a primary, run the rs.conf() method and assign the result to a variable:

cfg = rs.conf()

The returned document contains a members field which contains an array of member configuration documents, one document for each member of the replica set.

2

Assign priority value of 0.

To prevent a secondary member from becoming a primary, update the secondary member’s members[n].priority to 0.

To assign a priority value to a member of the replica set, access the member configuration document using the array index. In this tutorial, the secondary member to change corresponds to the configuration document found at position 2 of the members array.

cfg.members[2].priority = 0

The configuration change does not take effect until you reconfigure the replica set.

3

Reconfigure the replica set.

Use rs.reconfig() method to reconfigure the replica set with the updated replica set configuration document.

Pass the cfg variable to the rs.reconfig() method:

rs.reconfig(cfg)