翻译或纠错本页面

复制集的安全写级别

无论是单节点 的还是 复制集 的MongoDB,对于应用程序来说,都是透明的。 然而,复制集为写操作也提供了一些配置选项。 [1]

[1]Sharded clusters where the shards are also replica sets provide the same configuration options with regards to write and read operations.

复制集写操作的审核

For a replica set, the default write concern requests acknowledgement only from the primary. You can, however, override this default write concern, such as to confirm write operations on a specified number of the replica set members.

Write operation to a replica set with write concern level of ``w:2`` or write to the primary and at least one secondary.

我们可以在每次写操作的时候指定安全写级别来规避默认的安全写级别。例如,下面的语句指定了安全写级别,那么这个写操作只有在超时超过5秒或是已经在主节点与一个从节点上应用后才会返回。

db.products.insert(
   { item: "envelopes", qty : 100, type: "Clasp" },
   { writeConcern: { w: 2, wtimeout: 5000 } }
)

我们可以在安全写级别中设定超时限制。这样可以在写操作无法到达目标服务器的时候造成的堵塞。举个例子,当复制集只有3成员,而安全写级别设置的需要复制集的4个成员确认的时,该操作就会一直堵塞直到获得4个成员的确认。详情参见 wtimeout

Modify Default Write Concern

You can modify the default write concern for a replica set by setting the settings.getLastErrorDefaults setting in the replica set configuration. The following sequence of commands creates a configuration that waits for the write operation to complete on a majority of the voting members before returning:

cfg = rs.conf()
cfg.settings = {}
cfg.settings.getLastErrorDefaults = { w: "majority", wtimeout: 5000 }
rs.reconfig(cfg)

如果在执行写操作的时候指定了安全写级别,那么该写操作将会使用指定的安全写级别而不是默认的。

参见

Write Concern

Custom Write Concerns

You can tag the members of replica sets and use the resulting tag sets to create custom write concerns. See 配置复制集标签设置 for information on configuring custom write concerns using tag sets.