ここら辺を参考に試してみる
mongoDBでシャーディング+レプリカセットしてみる - Qiita
シャーディングとレプリカセットを組み合わせて構築する
構成
レプリカセットの構築
rs1,rs2を作っていく
# rs1 sudo mongod --port 27041 --dbpath /data/mongo/repl1 --logpath /data/mongo/repl1/log --fork --replSet rs1 sudo mongod --port 27042 --dbpath /data/mongo/repl2 --logpath /data/mongo/repl2/log --fork --replSet rs1 sudo mongod --port 27043 --dbpath /data/mongo/repl3 --logpath /data/mongo/repl3/log --fork --replSet rs1 # rs2 sudo mongod --port 27051 --dbpath /data/mongo/repl4 --logpath /data/mongo/repl4/log --fork --replSet rs2 sudo mongod --port 27052 --dbpath /data/mongo/repl5 --logpath /data/mongo/repl5/log --fork --replSet rs2 sudo mongod --port 27053 --dbpath /data/mongo/repl6 --logpath /data/mongo/repl6/log --fork --replSet rs2
$ mongo localhost:27041 > config = {_id: "rs1", members: [ {_id: 0, host: 'localhost:27041'}, {_id: 2, host: 'localhost:27042'},{_id: 3, host: 'localhost:27043'} ] } > rs.initiate(config)
$ mongo localhost:27051 > config = {_id: "rs2", members: [ {_id: 0, host: 'localhost:27051'}, {_id: 2, host: 'localhost:27052'},{_id: 3, host: 'localhost:27053'} ] } > rs.initiate(config)
これでレプリカセットが2つできました
シャーディングを設定する
- configサーバの起動
sudo mkdir /data/mongo/shardconfig sudo mongod --configsvr --port 27031 --dbpath=/data/mongo/shardconfig --logpath /data/mongo/shardconfig/log --fork
- mongosの起動
sudo mkdir /data/mongo/shardmongos sudo mongos --port 27017 --configdb localhost:27031 --chunkSize 1 --logpath /data/mongo/shardmongos/log --fork
設定時にreplicaset名/replicasetのメンバー,,をカンマ区切りで記述する
$ mongo localhost:27017 > db.adminCommand({addshard: "rs1/localhost:27041,localhost:27042,localhost:27043", name: "rs1", allowLocal: true}) > db.adminCommand({addshard: "rs2/localhost:27051,localhost:27052,localhost:27053", name: "rs2", allowLocal: true}) > sh.status()
シャーディング対象のDBを設定
今回はlogs
というDBに対してシャーディングを行う
> use admin > db.runCommand({ enablesharding: "logs"}); > sh.shardCollection("logs.apilogs",{"id": 1})
- データを投入してみる
mongoimport --port 27017 --db logs --collection apilogs --type json --file sample.log
$ mongo localhost:27017 mongos> db.apilogs.count() 57397 $ mongo localhost:27041 rs1:PRIMARY> db.apilogs.count() 27334 $ mongo localhost:27051 rs2:PRIMARY> db.apilogs.count() 30063
件数は合いました
また、各slaveでも件数が同じことが確認できた