在Linux环境下,MongoDB的分片(Sharding)是一种用于扩展数据库存储和处理大量数据的技术。以下是进行MongoDB分片的基本步骤:
配置服务器存储集群的元数据。通常需要三个配置服务器以实现高可用性。
mongod --configsvr --replSet configReplSet --dbpath /data/configdb --port 27019
然后初始化配置服务器副本集:
mongo --port 27019
rs.initiate(
{
_id: "configReplSet",
configsvr: true,
members: [
{ _id : 0, host : "cfg1.example.com:27019" },
{ _id : 1, host : "cfg2.example.com:27019" },
{ _id : 2, host : "cfg3.example.com:27019" }
]
}
)
每个分片节点也是一个副本集的一部分。
mongod --shardsvr --replSet shardReplSet --dbpath /data/shard1 --port 27018
然后初始化分片副本集:
mongo --port 27018
rs.initiate(
{
_id: "shardReplSet",
members: [
{ _id : 0, host : "shard1a.example.com:27018" },
{ _id : 1, host : "shard1b.example.com:27018" },
{ _id : 2, host : "shard1c.example.com:27018" }
]
}
)
mongos是MongoDB的分片路由器,客户端通过它连接到分片集群。
mongos --configdb configReplSet/cfg1.example.com:27019,cfg2.example.com:27019,cfg3.example.com:27019 --port 27017
连接到mongos并添加分片。
mongo --port 27017
sh.addShard("shardReplSet/shard1a.example.com:27018,shard1b.example.com:27018,shard1c.example.com:27018")
选择要分片的数据库和集合,并指定分片键。
sh.enableSharding("mydatabase")
sh.shardCollection("mydatabase.mycollection", { "shardKey": 1 })
检查分片集群的状态。
sh.status()
mongostat和mongotop)来监控集群的性能。通过以上步骤,你可以在Linux环境下成功配置和运行MongoDB的分片集群。