在Linux上配置MongoDB分片集群涉及多个步骤,包括设置配置服务器、分片服务器和路由服务器(mongos)。以下是一个基本的指南:
确保你已经安装了MongoDB,并且所有节点都可以通过网络互相通信。
配置服务器存储分片集群的元数据。你需要至少三个配置服务器以实现高可用性。
# 在每个配置服务器上启动mongod
mongod --configsvr --replSet <configReplSetName> --dbpath /data/configdb --port 27019
例如:
mongod --configsvr --replSet configReplSet --dbpath /data/configdb --port 27019
连接到其中一个配置服务器并初始化副本集。
mongo --port 27019
在mongo shell中执行:
rs.initiate(
{
_id: "configReplSetName",
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。
mongod --shardsvr --replSet <shardReplSetName> --dbpath /data/db --port 27018
例如:
mongod --shardsvr --replSet shard1 --dbpath /data/db --port 27018
初始化分片副本集:
mongo --port 27018
在mongo shell中执行:
rs.initiate(
{
_id: "shard1",
members: [
{ _id : 0, host : "shard1a.example.com:27018" },
{ _id : 1, host : "shard1b.example.com:27018" },
{ _id : 2, host : "shard1c.example.com:27018" }
]
}
)
在每个mongos实例上启动mongos。
mongos --configdb configReplSetName/cfg1.example.com:27019,cfg2.example.com:27019,cfg3.example.com:27019 --port 27017
连接到mongos并添加分片。
mongo --port 27017
在mongo shell中执行:
sh.addShard("shard1/shard1a.example.com:27018,shard1b.example.com:27018,shard1c.example.com:27018")
连接到mongos并启用数据库和集合分片。
sh.enableSharding("mydatabase")
sh.shardCollection("mydatabase.mycollection", { "shardKey": 1 })
连接到mongos并查看分片集群的状态。
sh.status()
以上步骤涵盖了在Linux上配置MongoDB分片集群的基本过程。实际部署时,可能需要根据具体需求进行调整,例如配置更多的分片、副本集成员,或者调整网络设置等。确保在生产环境中使用安全的网络配置和适当的硬件资源。