mongoDB系列之(三):mongoDB 分片


1. monogDB的分片(Sharding)

分片是mongoDB針對TB級別以上的數據量,采用的一種數據存儲方式。

mongoDB采用將集合進行拆分,然后將拆分的數據均攤到幾個mongoDB實例上的一種解決方案。

分片模式下,mongoDB實例分為三種:

shards: 存儲數據的mongoDB

config: 保存設定的monogDB

routing(mongos): 負責分片處理的mongoDB

2. 配置分片

2.1 試驗環境

1 mongos, 1 config, 2 shard

config:  test166:27019
mongos:  test166:27020
shards:  test166:27017,test167:27017

mongoDB都是單台構成,沒有使用副本集

2.2 啟動config

在test166上啟動config實例,端口27019

# mongod --configsvr --dbpath /var/lib/mongo-c --port 27019

2.3 啟動 mongos

在test166上啟動routing實例,端口27020

# mongos --configdb test166:27019 --port 27020

2.4 啟動 shards

在test166和test167上分別啟動shards

# /etc/init.d/mongod start

2.5 添加shards

連接monogs

# mongo --port 27020

添加shards

mongos> use admin
mongos> sh.addShard( "test166:27017" )
mongos> sh.addShard( "test167:27017" )

確認

mongos> db.runCommand({listshards:1})

2.6 開啟分片

對指定的庫開啟sharding

mongos> sh.enableSharding("new")

指定分片的片鍵

片鍵有兩種模式:hash模式,range模式

2.6.1 使用hash模式分片

mongos> sh.shardCollection( "new.person", { "_id": "hashed" } )

插入數據確認

mongos> use new
mongos> for(var i=0;i<10;i++){db.person.insert({name:"bluejoe"+i});}

使用hash模式,記錄在各片上的分布比較平均

2.6.2 使用range模式分片

mongos> sh.shardCollection( "new.person2", { "name": 1 } )

插入數據確認

mongos> use new
mongos> for(var i=0;i<100;i++){db.person2.insert({name:"jack"+i});}

2.7 確認分片情況

mongos> sh.status()
或
mongos> db.printShardingStatus()

在各shard上確認數據分布情況(hash模式)

> use new
> db.person.find()

test166:27017上的數據分布情況

test167:27017上的數據分布情況

2.8 其他

要分片的庫原來有數據的情況下,先建index,然后再指定片鍵

mongos> sh.enableSharding("new2")
mongos> use new2
mongos> db.user2.createIndex( { "username": 1 } )
mongos> sh.shardCollection( "new2.user2", { "username": 1 } )

3. 后記

本次測試環境使用mongoDB單台構成,沒有使用副本集,使用副本集時的分片配置和上面類似,在此不詳述。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM