mongodb/shardingを試してみた

mongod, mongoc(mongod), mongos

mkdir tmp/d1 tmp/d2 tmp/d3 tmp/c1 tmp/c2 tmp/c3
mongod --shardsvr --dbpath tmp/d1 --logpath tmp/d1.log --port 27031 --fork
mongod --shardsvr --dbpath tmp/d2 --logpath tmp/d2.log --port 27032 --fork
mongod --shardsvr --dbpath tmp/d3 --logpath tmp/d3.log --port 27033 --fork
mongod --configsvr --dbpath tmp/c1 --logpath tmp/c1.log --port 27011 --fork
mongod --configsvr --dbpath tmp/c2 --logpath tmp/c2.log --port 27012 --fork
mongod --configsvr --dbpath tmp/c3 --logpath tmp/c3.log --port 27013 --fork
mongos --configdb localhost:27011,localhost:27012,localhost:27013 --logpath tmp/s1.log --chunkSize 1 --port 27021 --fork

mongocはconfig server、mongosはshardを管理する。

sharding設定

mongo localhost:27021

mongos> use admin
mongos> db.runCommand({"addShard":"localhost:27031"})
mongos> db.runCommand({"addShard":"localhost:27032"})
mongos> db.runCommand({"addShard":"localhost:27033"})
mongos> db.adminCommand({"enableSharding":"blog"})
mongos> db.adminCommand({"shardCollection":"blog.user",key:{"userId":1}, unique:true});

use admin、管理権限で作業する

shard keyはカーディナリティの高いキーを選ばないとshardが偏ってしまい負荷が平準化されない

blog collectionの登録(10万件)

mongos> use blog
for(var i=1; i <= 100000; i++){
     var user = {
          userId : i,
          name : "userName"+i,
          createAt : new Date().getTime()
     }
     db.user.save(user);
}

shardされているか確認

echo "db.user.count()" | mongo localhost:27031/blog
echo "db.user.count()" | mongo localhost:27032/blog
echo "db.user.count()" | mongo localhost:27033/blog

shardされているか確認(実行結果つき)

-> %     echo "db.user.count()" | mongo localhost:27031/blog
MongoDB shell version: 2.4.4
connecting to: localhost:27031/blog
22077
bye
-> %     echo "db.user.count()" | mongo localhost:27032/blog
MongoDB shell version: 2.4.4
connecting to: localhost:27032/blog
44385
bye
-> %     echo "db.user.count()" | mongo localhost:27033/blog
MongoDB shell version: 2.4.4
connecting to: localhost:27033/blog
33538
bye