请写出MongoDB创建副本和分片的步骤和配置文件。
时间: 2024-03-25 21:37:18 浏览: 109
MongoDB创建副本和分片的步骤如下:
1. 创建副本集
- 启动MongoDB实例,设置--replSet参数,指定副本集名称,例如:mongod --replSet rs0
- 进入Mongo shell,执行rs.initiate()初始化副本集
- 添加副本集成员,例如:rs.add("192.168.0.2:27017")
2. 配置副本集
- 在Mongo shell中执行rs.conf(),获取当前副本集配置
- 修改副本集配置,例如:cfg.members[0].priority=2
- 在Mongo shell中执行rs.reconfig(cfg),应用新的配置
3. 创建分片集群
- 启动MongoDB实例,设置--shardsvr参数,指定实例为分片节点,例如:mongod --shardsvr
- 启动MongoDB实例,设置--configsvr参数,指定实例为配置节点,例如:mongod --configsvr
- 启动MongoDB实例,设置--mongos参数,指定实例为mongos路由节点,例如:mongos --configdb configserver/localhost:27019,localhost:27020,localhost:27021
4. 添加分片
- 在Mongo shell中执行sh.addShard(),添加分片节点,例如:sh.addShard("rs0/192.168.0.2:27017")
配置文件示例:
- 副本集配置文件:
```
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
storage:
dbPath: "/var/lib/mongodb"
journal:
enabled: true
processManagement:
fork: true
pidFilePath: "/var/run/mongodb/mongod.pid"
net:
port: 27017
bindIp: "0.0.0.0"
replication:
replSetName: "rs0"
```
- 分片节点配置文件:
```
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
storage:
dbPath: "/var/lib/mongodb"
journal:
enabled: true
processManagement:
fork: true
pidFilePath: "/var/run/mongodb/mongod.pid"
net:
port: 27018
bindIp: "0.0.0.0"
sharding:
clusterRole: shardsvr
```
- 配置节点配置文件:
```
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
storage:
dbPath: "/var/lib/mongodb"
journal:
enabled: true
processManagement:
fork: true
pidFilePath: "/var/run/mongodb/mongod.pid"
net:
port: 27019
bindIp: "0.0.0.0"
sharding:
clusterRole: configsvr
```
- mongos路由节点配置文件:
```
systemLog:
destination: file
path: "/var/log/mongodb/mongos.log"
logAppend: true
processManagement:
fork: true
pidFilePath: "/var/run/mongodb/mongos.pid"
net:
port: 27017
bindIp: "0.0.0.0"
sharding:
configDB: configserver/localhost:27019,localhost:27020,localhost:27021
```
阅读全文