MongoDB副本集搭建

版本

> db.version()
4.4.24
> 

集群相关命令

rs.status()

## id 要和配置文件定义的replSetName一致
cfg={_id:"knight",members:[{_id:0,host:'182.27.239.17:27017',priority:1}]}

##  id 要和配置文件定义的replSetName一致
cfg={_id:"knight",members:[{_id:0,host:'10.1.1.32:27017',priority:1},{_id:1,host:'10.1.1.33:27017',priority:0,votes:0}]}

##
cfg={_id:"knight",members:[{_id:0,host:'10.1.1.32:27017',priority:1},{_id:1,host:'10.1.1.33:27017',priority:0}]}

## 
rs.initiate(cfg)  
 
## 查看配置
rs.conf()

###
rs.reconfig(config,{force:true})


### 查看配置
rs.config()
rs.config().members

参考

##
https://blog.csdn.net/GotFull/article/details/127034877


### 副本集无效
https://www.coder.work/article/544115

配置文件

systemLog:
   destination: file
   path: "/opt/app/mongodb_cluster/log/m27071.log"
   logAppend: true
processManagement:
   fork: true
   pidFilePath: "/opt/app/mongodb_cluster/pid/m27071.pid"
net:
   port: 27017
   bindIp: 0.0.0.0
#   http:
#     enabled: true
#     RESTInterfaceEnabled: true

storage:
   dbPath: "/opt/app/data/27071"
   engine: wiredTiger
   journal:
      enabled: true
   directoryPerDB: true
   wiredTiger:
      engineConfig:
          cacheSizeGB: 1
          directoryForIndexes: true

# 定义复制集的名称
replication:
   oplogSizeMB: 800
   replSetName: "rs"

集群配置

初始化

在主节点上执行命令如下:

# 执行命令
rs.initiate()

####
#若客户端返回信息中字段OK的值为1,说明成功初始化副本集。
#完成初始化命令,当前节点默认处于"SECONDARY(副本节点)"状态.
###等待几秒后,按回车键。自动选举自己为PRIMARY(主节点)

添加成员节点

## 先默认初始化
rs.initiate()   

## 
cfg={_id:"xbrother",members:[{_id:0,host:'10.1.1.32:27017',priority:1},{_id:1,host:'10.1.1.33:27017',priority:0}]}

##
rs.initiate(cfg)   

检查和测试

# 检查状态
rs.status()

## 主节点写入数据测试
rs:PRIMARY> db.user.insert({"name":"knight","age":30})
WriteResult({ "nInserted" : 1 })
rs:PRIMARY> db.user.find()
{ "_id" : ObjectId("64f9b892e61da94af298a9d3"), "name" : "knight", "age" : 30 }
rs:PRIMARY> 



### 从节点查询数据
#### 从库开启读
rs:SECONDARY> rs.secondaryOk()

##
rs:SECONDARY> use test
switched to db test
rs:SECONDARY> db.user.find()
{ "_id" : ObjectId("64f9b892e61da94af298a9d3"), "name" : "knight", "age" : 30 }
rs:SECONDARY> 

你可能感兴趣的:(#,MongoDB,mongoDB)