Mongodb中數據分片叫做chunk,它是一個Collection中的一個連續的數據記錄,但是它有一個大小限制,不可以超過200M,如果超出產生新的分片。
下面是一個簡單的分片集群實例
分片集群的構成:
- Shard server:mongod實例,用于存儲實際的數據塊
- Config server:mongod實例,用于存儲整個Cluster Metadata,其中包括chunk信息。
- Route server:mongos實例,做為整個集群的前端路由,整個集群由此接入。從而讓整個集群看著像單一進程數據庫。
- 備注:route做為路由會將請求轉發到實際的目標服務進程,并將多個結果合并并回傳客戶端。在route并不存儲任何的數據和狀態,所有的信息都是啟動的時候從Config server上獲取,當Config server上有信息更新,也會同步到route server上。
構建一個簡單的集群
集群目錄:
總共有四個mongodb,目錄分別為/home/scotte.ye/mongo1,mongo2,mongo3,mongo4
其中mongo1,mongo2做為shard server
mongo3做為config server
mongo4做為route server
1、啟動Shard server
// 啟動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
//啟動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
//啟動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
//啟動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
//注在啟動Route server的時候,還可以通過-chunksize參數來進行配置分塊的大小
2、配置相關
配置相關命令說明:
- addshard:添加shard server到集群。相類似的命令還有,listshards和removeshard
- enablesharding:用于設置那些數據庫可以被分布存儲
- shardcollection:用于設置具體被分片的集合的名稱,且必須指定 share key,系統會自動創建索引
- 注:shardcollection的集合必須只有一個unique index且必須是shard key
開始配置:
$ cd /home/scotte.ye/mongo3/bin
$ ./mongo
$ >use admin
$#只有在admin數據庫才可以操作
$ 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}
$#添加相應到shard server到shard cluster
$ >db.runCommand({enablesharding:'test'})
$#使相應的數據庫表test可以分布存儲,test可以更換成相應的其它數據庫名字
$ >db.runCommand({sahrdcollection:'test.user',key:{_id:1}})
$ {"OK":1}
$#指明相應的集合和shard key
$ {"collectionsharded":"test.user","OK":1}
3、常用的狀態查詢命令
- printShardingStatus():查看Sharding信息
- db.<collection_name>.stats():查看具體shard存儲信息
- isdbgrid:用于確認當前是否是sharding cluster
- ismaster:判斷是不是master