MongoDB数据库分片及副本集配置
1、配置分片服务,建立安装路径和分片端口号,启动分片服务
在MongoDB安装目录文件下创建shard文件,shard文件下创建s0、s1、s2等文件
2、将MongoDB文件下的bin、log、data复制到s0、s1、s2、s3的data文件下并建一个db文件(有就不建)。
3、配置s0:进入Windows命令提示符窗口,进入D:\MongoDB\shard\s0\data\bin下执行命令
mongod --port 27020 -dbpath "d:\MongoDB\shard\s0\data\db" -logpath "d:\MongoDB\shard\s0\data\log\s0.log" --logappend –shardsvr
S1、s2、s3的配置相同
mongod --port 27021 -dbpath "d:\MongoDB\shard\s1\data\db" -logpath "d:\MongoDB\shard\s1\data\log\s1.log" --logappend --shardsvr
mongod --port 27022 -dbpath "d:\MongoDB\shard\s2\data\db" -logpath "d:\MongoDB\shard\s2\data\log\s2.log" --logappend --shardsvr
mongod --port 27023 -dbpath "d:\MongoDB\shard\s3\data\db" -logpath "d:\MongoDB\shard\s3\data\log\s3.log" --logappend --shardsvr
除了在Windows命令提示符里面敲命令外还可以写批处理文件,s2、s3的配置就是通过写批处理文件进行的配置;如何写批处理文件呢?新建一个.txt文本文件,将命令写在此文本文件中,在将后缀名改为.bat;写好的批处理文件要放在bin目录下,然后双击这个文件执行即可。
批处理文件类容:
4、启动Config Server,在之前建的shard目录下建一个config文件,然后打开Windows命令提示窗口进入MongoDB\bin路径下输入命令配置主节点,当然你也可以写批处理文件。
mongod -port 27017 --configsvr -dbpath d:\mongoDB\shard\config -logpath d:\MongoDB\shard\log\config.log --logappend -replSet rs0
配置从节点需要将你安装的MongoDB实列复制两份放在D盘下,分别命名为MongoDB2和MongoDB3(当然你也可以命其他的名字,不过,命令里面的路径要更改)
打开Windows命令提示符,进入D:\MongoDB2\bin路径,输入命令。
mongod -port 27018 --configsvr -dbpath "d:\mongoDB2\data\db" -logpath "d:\MongoDB2\data\log\MongoDB.log" -replSet rs0
mongod -port 27019 --configsvr -dbpath "d:\mongoDB3\data\db" -logpath "d:\MongoDB3\data\log\MongoDB.log" -replSet rs0
5、设置副本集配置:打开Windows命令提示符,进入D:\MongoDB\bin(D:\MongoDB2\bin和D:\MongoDB3\bin下也可)路径,输入命令 Mongo -port 27017(你也可以打开27018或者27019端口)。然后输入配置指令。
Mongo -port 27017
use admin
config={_id: "rs0",members:[
{_id: 0, host: "localhost:27017","priority":3},
{_id: 1, host: "localhost:27018","priority":2},
{_id: 2, host: "localhost:27019","priority":1},
]
}
rs.initiate(config)
6、启动Route Process
mongos -port 40000 -configdb "rs0/localhost:27017,localhost:27018,localhost:27019" -logpath "d:\MongoDB\shard\log\route.log"
7、配置Sharding,添加分片节点。
`mongo admin --port 40000
db.runCommand({addShard:"localhost:27020"})
db.runCommand({addShard:"localhost:27021"})
db.runCommand({addShard:"localhost:27022"})
db.runCommand({addShard:"localhost:27023"})
查看分片服务器配置
db.runCommand({listshards:1})

设置分片存储的数据库和集合
db.runCommand({enablesharding:"bookdb"})
db.runCommand({shardcollection:"bookdb.books",key:{id:1}})
显示数据库分片信息
sh.status()