mongodb版本3.2.7
资源划分:
192.168.1.11:27017----》config server
192.168.1.11:27018----》mongos
192.168.1.11:27019----》mongod服务
192.168.1.11:27020----》mongod服务
由于都是在同一台机器上搭建的,所以这里都采取单一模式,当然你可以将mongod服务做成副本集,config server也可以做成副本集,这里不再赘述
直接贴配置:
192.168.1.11:27017
path: /var/log/mongodb/mongod.log
dbPath: /mongodb/data
pidFilePath: /var/run/mongodb/mongod1.pid
port: 27017
bindIp: 192.168.1.11
sharding:
clusterRole: configsvr
然后启动config server
mongod -f /etc/mongod.conf
192.168.1.11:27018--->mongos
#storage:
#dbPath: /mongodb2/data
#journal:
# enabled: true
将上面几个选项注释掉,如果不注释会出现下面错误:
path: /var/log/mongodb/mongod2.log
pidFilePath: /var/run/mongodb/mongod2.pid
port: 27018
bindIp: 192.168.1.11
sharding:
configDB: 192.168.1.11:27017
然后启动服务:
mongos --config mongod.conf
192.168.1.11:27019
path: /var/log/mongodb/mongod3.log
dbPath: /mongodb3/data
pidFilePath: /var/run/mongodb/mongod3.pid
port: 27019
bindIp: 192.168.1.11
sharding:
clusterRole: shardsvr
然后启动服务:
mongod -f <path-to-config>
192.168.1.11:27020
path: /var/log/mongodb/mongod4.log
dbPath: /mongodb4/data
pidFilePath: /var/run/mongodb/mongod4.pid
port: 27020
bindIp: 192.168.1.11
sharding:
clusterRole: shardsvr
然后启动服务:
mongod -f <path-to-config>
查看端口是否被监听
然后登陆mongos
mongo --host 192.168.1.11 --port 27018
然后进行添加sharding
然后再次查看sharding状态如下图:
可以明显的看出添加成了两个分区sharding,
mongos>sh.enableSharding(testdb)---->对testdb启用sharding分区
mongos>sh.shardCollection(fullName,key,unique)---->对collection进行分区
sh.shardCollection("huangdb.testcoll",{Age:1,Name:1}):根据年龄和名字做顺序分区
for (i=1;i<=100000;i++) db.testcoll.insert({Name:"user"+i,Age:(i%100),Address:"#"+i})
利用上述命令将db,collection进行分区分片
参考文章:https://docs.mongodb.com/manual/tutorial/deploy-shard-cluster/