本文基于:MongoDB 读写分离——MongoDB 安装

参考:https://docs.mongodb.com/manual/tutorial/deploy-replica-set-for-testing/

Master-Slave 主从复制

实现数据同步只需要在某一台服务器启动时加上"-master"参数,以指明此服务器的角色是primary;另一台服务器加上"-slave"和"-source"参数,以指明此服务器的角色是slave。

主从复制的优点如下:

  • 从服务器可以执行查询工作,降低主服务器访问压力。
  • 在从服务器执行备份,避免备份期间锁定主服务器的数据。
  • 当主服务器出现故障时,可以快速切换到从服务器,减少当机时间。

注意:MongoDB 的最新版本已不再推荐此方案。主从复制虽然可以承受一定的负载压力,但这种方式仍然是一个单点,如果主库挂了,数据写入就成了风险。

Replica Sets复制集

MongoDB 在 1.6 版本对开发了新功能replica set,这比之前的replication 功能要强大一 些,增加了故障自动切换和自动修复成员节点,各个DB 之间数据完全一致,大大降低了维 护成功。auto shard 已经明确说明不支持replication paris,建议使用replica set,replica set 故障切换完全自动。

Replica Sets的结构类似一个集群,完全可以把它当成一个集群,因为它确实与集群实现的作用是一样的:如果其中一个节点出现故障,其他节点马上会将业务接管过来而无须停机操作。

 

副本集需要3个节点,所以需要增加一个 Server.4.2.27019

修改 Server.4.2.27017\bin 下面的 mongod.cfg

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: D:\Program Files\MongoDB\Server.4.2.27017\data
  journal:
    enabled: true
#  engine: wiredTiger
#  mmapv1:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 1

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path:  D:\Program Files\MongoDB\Server.4.2.27017\log\mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1


#processManagement:

#security:

#operationProfiling:

replication:
  replSetName: "rs0" #组名
oplogSize: 2000 # 默认下,oplog大小会占用64位的实例5%的可用磁盘空间。
#sharding: ## Enterprise-Only Options: #auditLog: #snmp:

可以在cmd 下运行 mongo 执行 rs.initiate(),这边使用的客户端工具执行 Studio3T.jar

MongoDB 读写分离——Windows MongoDB 副本集配置

 

 MongoDB 读写分离——Windows MongoDB 副本集配置

 

 将21018、21019 都设为 rs0 rs0

MongoDB 读写分离——Windows MongoDB 副本集配置

 

 MongoDB 读写分离——Windows MongoDB 副本集配置

 

 这时候三个都是只读的 rs.initiate()结果已经和只有一个的有所不同


 

初始化前可以 rs.status(),前后做个比较

MongoDB 读写分离——Windows MongoDB 副本集配置

 

 创建一个副本集配置对象,使用rs.initiate()初始化副本集,然后将rsconf文件传递给rs.initiate(),如下所示

如果出现“not master and slaveok=false”的提示错误,请输入一下命令 rs.slaveOK()

rsconf = {
   _id: "rs0",
   members: [
     {
      _id: 0,
      host: "127.0.0.1:27017" 【这个要是对外IP,否则代码连接时,会转到本地127.0.0.1地址】
     },
     {
      _id: 1,
      host: "127.0.0.1:27018"
     },
     {
      _id: 2,
      host: "127.0.0.1:27019"
     }
    ]
}
rs.initiate(rsconf)

MongoDB 读写分离——Windows MongoDB 副本集配置

 

MongoDB 读写分离——Windows MongoDB 副本集配置

 

 刷新左侧列表

 MongoDB 读写分离——Windows MongoDB 副本集配置

 

 

运行 db.isMaster() 看效果

MongoDB 读写分离——Windows MongoDB 副本集配置

 

相关文章: