Mongodb - 切片搭建
0.概述
mongodb分片搭建,版本号4.0.2,以下除了创建opt文件夹以外,所有操作均在mongodb用户下面执行
准备三台机器:
192.168.56.81
192.168.56.82
192.168.56.83
配置服务器端口号:20000
路由服务器端口号:20004
分片服务器端口号:20001/20002/20003
1.启动Config Server,端口号设置为20000
(把以下的步骤分别在三台服务器中执行一遍)
mkdir /opt
chown mongodb:mongodb /opt
su - mongodb
cd /opt
mkdir -p ./shard/config
mkdir -p ./shard/config/data
mkdir -p ./shard/config/log
mongod --configsvr --dbpath=/opt/shard/config/data --logpath=/opt/shard/config/log/config.log --port 20000 --fork --logappend --replSet rsconf --bind_ip_all
2.在其中一台初始化Config Server集群
192.168.56.81:
mongo --port 20000
use admin
config = {_id: 'rsconf', members: [
{_id: 0, host: '192.168.56.81:20000'},
{_id: 1, host: '192.168.56.82:20000'},
{_id: 2, host: '192.168.56.83:20000'}]}
rs.initiate(config)
rs.conf()
rs.status()
3.启动Query Routers,端口号设置为20004
(把以下的步骤分别在三台服务器中执行一遍)
cd /opt
mkdir -p ./shard/mongos
mkdir -p ./shard/mongos/log
mongos --configdb rsconf/192.168.56.81:20000,192.168.56.82:20000,192.168.56.83:20000 --logpath=/opt/shard/mongos/log/mongos.log --port 20004 --fork --logappend
4.启动Shard Server 1,集群名字rs1,端口号20001
(把以下的步骤分别在三台服务器中执行一遍)
cd /opt
mkdir -p ./shard/replset/rs1/data
mkdir -p ./shard/replset/rs1/log
mongod --shardsvr --replSet rs1 --dbpath=/opt/shard/replset/rs1/data --logpath=/opt/shard/replset/rs1/log/rs1.log --fork --port 20001 --logappend --bind_ip_all
5.在其中一台初始化Shard Server副本集
192.168.56.81:
mongo --port 20001
use admin
config = {_id: 'rs1', members: [
{_id: 0, host: '192.168.56.81:20001'},
{_id: 1, host: '192.168.56.82:20001'},
{_id: 2, host: '192.168.56.83:20001', 'arbiterOnly':true}]}
rs.initiate(config)
6.重复第4,5步
注意修改 rs1 --> rs2, rs3
注意修改 20001 --> 20002, 20003
7.登陆mongos路由
192.168.56.81:
mongo --port 20004
use admin
db.runCommand({"addshard":"rs1/192.168.56.81:20001,192.168.56.82:20001,192.168.56.83:20001"});
db.runCommand({"addshard":"rs2/192.168.56.81:20002,192.168.56.82:20002,192.168.56.83:20002"});
db.runCommand({"addshard":"rs3/192.168.56.81:20003,192.168.56.82:20003,192.168.56.83:20003"});
激活分片
db.runCommand({"enableSharding":"test"}); #test是数据库名字
db.runCommand({"shardCollection":"test.students",key:{name:1}}); #test.students是集合名字
8.查看分片的状态
db.printShardingStatus()
9.验证分片情况
for (var x=1; x<200000; x++) {
db.students.insert({"name":"fuckmongo - " + x,"stuid":x});
}
for (var x=1; x<200000; x++) {
db.students.insert({"name":"lovemongo - " + x,"stuid":x});
}
for (var x=1; x<200000; x++) {
db.students.insert({"name":"hatemongo - " + x,"stuid":x});
}
for (var x=1; x<2000000; x++) {
db.students.insert({"name":"moremongo - " + x,"stuid":x});
}
rs.status()
db.students.stats()