1.前言
找了很多书,发现对分片的搭建还是有模糊,所以这一次记一下。
2.搭建环境
一共四台主机
ip | 职能 |
192.168.0.124 | config、mongos |
192.168.0.125 | share1 |
192.168.0.126 | share2 |
192.168.0.127 | share3 |
他们的结构是这样的
是很简单的一个架构。
3.开始配置
- 先配置三台share2,我用的是mongodb3.4,在0.125、0.126、0.127三台主机上敲以下命令
[root@linux]#mkdir /share/shaer125
[root@linux]#mongod -shardsvr -port 27017 -dbpath=/share/share125 -logpath=/share/share125.log
- 记得要把125给替换一下,启动不成功请自己去排查原因
- 然后在config和mongos服务器下敲以下命令,首先先配置管理配置服务器。
mkdir /data/config
mongod --configsvr -port 20000 --dbpath=/data/config --logpath=/data/config.log
- 然后配置我们的mongos服务器,就是主控端
mongos -configdb 192.168.0.124:20000 --pot 27019 --logpath=/data/mongos.log
- 到目前为止,我们四台服务器的mongodb都已经启动成功了,然后要链接mongos,去将分片连接起来,开启一个mongo窗口,连接124.然后执行添加分片命令
sh.addShard('192.168.0.125:27017')
sh.addShard('192.168.0.126:27017')
sh.addShard('192.168.0.127:27017')
- 然后执行db.printShardingStatus();可发现,已经添加了分片机
--- Sharding Status ---
sharding version: {
"_id" : 1,
"minCompatibleVersion" : 5,
"currentVersion" : 6,
"clusterId" : ObjectId("585ba088d6d7ae8dc748cb21")
}
shards:
{ "_id" : "shard0000", "host" : "192.168.0.125:27017" }
{ "_id" : "shard0001", "host" : "192.168.0.126:27017" }
{ "_id" : "shard0002", "host" : "192.168.0.127:27017" }
active mongoses:
"3.2.11" : 1
balancer:
Currently enabled: yes
Currently running: no
Failed balancer rounds in last 5 attempts: 0
Migration Results for the last 24 hours:
No recent migrations
- 然后我们要给我们的集合添加数据库和聚合了。
sh.enableSharding("testdb");
{"ok":1}
sh.shardCollection("testdb.testcollection",{testkey:1})
- 以上就是首先分片testdb数据库,然后对这个数据库中的testcollection这个聚合中的testkey键值添加分片的参数。
- 执行完以后,使用db.printShardingStatus();查看
--- Sharding Status ---
sharding version: {
"_id" : 1,
"minCompatibleVersion" : 5,
"currentVersion" : 6,
"clusterId" : ObjectId("585ba088d6d7ae8dc748cb21")
}
shards:
{ "_id" : "shard0000", "host" : "192.168.0.125:27017" }
{ "_id" : "shard0001", "host" : "192.168.0.126:27017" }
{ "_id" : "shard0002", "host" : "192.168.0.127:27017" }
active mongoses:
"3.2.11" : 1
balancer:
Currently enabled: yes
Currently running: no
Failed balancer rounds in last 5 attempts: 0
Migration Results for the last 24 hours:
No recent migrations
databases:
{ "_id" : "testdb", "primary" : "shard0000", "partitioned" : true }
testdb.testcolleciton
shard key: { "testkey" : 1 }
unique: false
balancing: true
chunks:
shard0000 1
{ "_id" : { "$minKey" : 1 } } -->> { "_id" : { "$maxKey" : 1 } } on : shard0000 Timestamp(1, 0)
到这里就基本的配置完毕,后期还要设置索引。