我第一次在 Windows 上设置了一个 MongoDB 分片集群,如下所述:http: //docs.mongodb.org/manual/tutorial/deploy-shard-cluster/
我使用以下脚本来启动配置服务器、mongos 实例和 mongo 数据服务器。
function get-cnfgServerObj($port, $path) {
$firstCnfgSrv = New-Object PSObject
$firstCnfgSrv | Add-Member Noteproperty -Name Port -value $port
$firstCnfgSrv | Add-Member Noteproperty -Name Path -value $path
return $firstCnfgSrv;
}
$mongodPath = "..\mongod.exe"
$mongosPath = "..\mongos.exe"
$cnfgServers = @(
(get-cnfgServerObj -port 20001 -path "..\data\configdb20001"),
(get-cnfgServerObj -port 20002 -path "..\data\configdb20002"),
(get-cnfgServerObj -port 20003 -path "..\data\configdb20003")
)
$dataServers = @(
(get-cnfgServerObj -port 27001 -path "..\data\shdb1"),
(get-cnfgServerObj -port 27002 -path "..\data\shdb2")
)
# Create the mongo config servers first
$cnfgServers | foreach {
if((Test-Path $_.Path) -eq $false)
{
New-Item -Path $_.Path -ItemType Directory
}
$args = "--configsvr --dbpath $($_.Path) --port $($_.Port)"
start-process $mongodPath $args -windowstyle Normal
}
# Create the mongo servers
$dataServers | foreach {
if((Test-Path $_.Path) -eq $false)
{
New-Item -Path $_.Path -ItemType Directory
}
$args = "--dbpath $($_.Path) --port $($_.Port)"
start-process $mongodPath $args -windowstyle Normal
}
# Create the mongos instances
$mongosArgs = "--configdb localhost:20001,localhost:20002,localhost:20003"
start-process $mongosPath $mongosArgs -windowstyle Normal
运行上述脚本后,我连接了 mongos 实例:
mongo --host localhost --port 27017
后来,我添加了分片并在数据库和集合上启用了分片:
// add servers as shards
sh.addShard("localhost:27001")
sh.addShard("localhost:27002")
// Enable sharding on 'foo' db
sh.enableSharding("foo")
// Enable sharding on 'testData' collection of 'foo' database
sh.shardCollection("foo.testData", { "x": 1, "_id": 1 })
最后,我在 mongo shell(连接到 mongos 实例)中运行以下注释:
use foo
// init data
for (var i = 1; i <= 2500; i++) db.testData.insert( { x : i } )
后来,我连接到我的一个数据服务器:
mongo --host localhost --port 27001
当我尝试查看 testData 集合中的文档计数时,我看到数字是 2500,它代表所有文档的计数:
use foo
db.testData.count()
简单地说,数据并没有在所有分片之间进行负载平衡。我在这里做错了什么?
编辑:
这是 sh.status() 命令结果:
--- Sharding Status ---
sharding version: {
"_id" : 1,
"version" : 3,
"minCompatibleVersion" : 3,
"currentVersion" : 4,
"clusterId" : ObjectId("535673272850501ad810ff51")
}
shards:
{ "_id" : "shard0000", "host" : "localhost:27001" }
{ "_id" : "shard0001", "host" : "localhost:27002" }
databases:
{ "_id" : "admin", "partitioned" : false, "primary" : "config" }
{ "_id" : "test", "partitioned" : false, "primary" : "shard0000" }
{ "_id" : "foo", "partitioned" : true, "primary" : "shard0000" }
foo.testData
shard key: { "x" : 1, "_id" : 1 }
chunks:
shard0001 1
shard0000 1
{ "x" : { "$minKey" : 1 }, "_id" : { "$minKey" : 1 } } -
->> { "x" : 1, "_id" : ObjectId("53567411cb144434eb53f08d") } on : shard0001 Tim
estamp(2, 0)
{ "x" : 1, "_id" : ObjectId("53567411cb144434eb53f08d")
} -->> { "x" : { "$maxKey" : 1 }, "_id" : { "$maxKey" : 1 } } on : shard0000 Tim
estamp(2, 1)