持續對資料庫做資料寫入時,資料越多速度會越慢,而且也可以發現都是同一台伺服器很忙
主因就是因為沒有做 DB 和 collection 的 sharding。
透過 Java driver 想要做 sharding 時,可以利用以下的程式碼。
第一段會先做 DB 的 sharding,這部份的目的是讓 DB 在產生 collection 時,會自動把 collection 轉移到其他比較不忙碌的資料庫
第二段是做 collection 的 sharding,這部份就是將一個 collection 當中的資料分散給其他資料庫。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
BasicDBObject command = null ; CommandResult result = null ; DB db = mongo.getDB( "admin" ); // Set sharding to the database. command = new BasicDBObject( "enablesharding" , "db_name" ); result = db.command(command); System.out.println( "Enable sharding for database: " + command); System.out.println( "Result of enable sharding for database: " + result.toString()); // Set sharding to the collection. DBObject cmd = new BasicDBObject(); cmd.put( "shardcollection" , "db_name.coll_name" ); cmd.put( "key" , new BasicDBObject( "_id" , 1 )); result = db.command(cmd); System.out.println( "Enable sharding for collection: " + command); System.out.println( "Result of enable sharding for collection: " + result.toString()); |
其中要注意的是,要設定 sharding 之前要先將操作中的 DB 轉換成 admin。
而以 sharding collection 的部份來說,sharding 成功會回復類似這樣的 JSON。
1 2 3 4 5 |
{ "serverUsed" : "/127.0.0.1:30000" , "collectionsharded" : "db_name.coll_name" , "ok" : 1 } |
參考資料:
1、sh.enableSharding()
2、sh.shardCollection()
沒有留言:
張貼留言