Mongodb中數(shù)據(jù)分片叫做chunk,它是一個(gè)Collection中的一個(gè)連續(xù)的數(shù)據(jù)記錄,但是它有一個(gè)大小限制,不可以超過(guò)200M,如果超出產(chǎn)生新的分片。
下面是一個(gè)簡(jiǎn)單的分片集群實(shí)例
分片集群的構(gòu)成:
- Shard server:mongod實(shí)例,用于存儲(chǔ)實(shí)際的數(shù)據(jù)塊
- Config server:mongod實(shí)例,用于存儲(chǔ)整個(gè)Cluster Metadata,其中包括chunk信息。
- Route server:mongos實(shí)例,做為整個(gè)集群的前端路由,整個(gè)集群由此接入。從而讓整個(gè)集群看著像單一進(jìn)程數(shù)據(jù)庫(kù)。
- 備注:route做為路由會(huì)將請(qǐng)求轉(zhuǎn)發(fā)到實(shí)際的目標(biāo)服務(wù)進(jìn)程,并將多個(gè)結(jié)果合并并回傳客戶端。在route并不存儲(chǔ)任何的數(shù)據(jù)和狀態(tài),所有的信息都是啟動(dòng)的時(shí)候從Config server上獲取,當(dāng)Config server上有信息更新,也會(huì)同步到route server上。
構(gòu)建一個(gè)簡(jiǎn)單的集群
集群目錄:
總共有四個(gè)mongodb,目錄分別為/home/scotte.ye/mongo1,mongo2,mongo3,mongo4
其中mongo1,mongo2做為shard server
mongo3做為config server
mongo4做為route server
1、啟動(dòng)Shard server
// 啟動(dòng)shard server 1
$ cd /home/scotte.ye/mongo1
$ ./mongo -shardsvr -port 10000 -dbpath=/home/data/10000/ -fork -logpath=/home/log/10000/null
$ all output going to: /home/log/10000/null
$ fork process: 10657
//啟動(dòng)shard server 2
$ cd /home/scotte.ye/mongo2
$ ./mongo -shardsvr -port 10011 -dbpath=/home/data/10011/ -fork -logpath=/home/log/10011/null
$ all output going to: /home/log/10011/null
$ fork process: 10661
//啟動(dòng)Config server
$ cd /home/scotte.ye/mongo3
$ ./mongo -configsvr -port 20000 -dbpath=/home/data/20000/ -fork -logpath=/home/log/20000/null
$ all output going to: /home/log/20000/null
$ fork process: 10857
//啟動(dòng)Route server
$ cd /home/scotte.ye/mongo4
$ ./mongos -configdb 192.168.35.106:20000 -fork -logpath=/home/log/20000/null
$ all output going to: /home/log/20000/null
$ fork process: 10900
//注在啟動(dòng)Route server的時(shí)候,還可以通過(guò)-chunksize參數(shù)來(lái)進(jìn)行配置分塊的大小
2、配置相關(guān)
配置相關(guān)命令說(shuō)明:
- addshard:添加shard server到集群。相類似的命令還有,listshards和removeshard
- enablesharding:用于設(shè)置那些數(shù)據(jù)庫(kù)可以被分布存儲(chǔ)
- shardcollection:用于設(shè)置具體被分片的集合的名稱,且必須指定 share key,系統(tǒng)會(huì)自動(dòng)創(chuàng)建索引
- 注:shardcollection的集合必須只有一個(gè)unique index且必須是shard key
開(kāi)始配置:
$ cd /home/scotte.ye/mongo3/bin
$ ./mongo
$ >use admin
$#只有在admin數(shù)據(jù)庫(kù)才可以操作
$ switched to db admin
$ >db.runCommand({addshard:'192.168.35.106:10000'})
$ {"shardAdded":"shard0000","OK":1}
$ >db.runCommand({addshard:'192.168.35.106:10011'})
$ {"shardAdded":"shard0001","OK":1}
$#添加相應(yīng)到shard server到shard cluster
$ >db.runCommand({enablesharding:'test'})
$#使相應(yīng)的數(shù)據(jù)庫(kù)表test可以分布存儲(chǔ),test可以更換成相應(yīng)的其它數(shù)據(jù)庫(kù)名字
$ >db.runCommand({sahrdcollection:'test.user',key:{_id:1}})
$ {"OK":1}
$#指明相應(yīng)的集合和shard key
$ {"collectionsharded":"test.user","OK":1}
3、常用的狀態(tài)查詢命令
- printShardingStatus():查看Sharding信息
- db.<collection_name>.stats():查看具體shard存儲(chǔ)信息
- isdbgrid:用于確認(rèn)當(dāng)前是否是sharding cluster
- ismaster:判斷是不是master