搭建MongoDB分片集群在CentOS上可以分为几个步骤。以下是一个基本的指南:
在所有节点上安装MongoDB。你可以使用MongoDB官方提供的YUM仓库来安装。
# 导入MongoDB公钥
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
# 创建MongoDB列表文件
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
# 更新包列表
sudo apt-get update
# 安装MongoDB
sudo apt-get install -y mongodb-org
# 启动MongoDB服务
sudo systemctl start mongod
# 设置MongoDB开机自启动
sudo systemctl enable mongod
假设你有三个节点:shard1, shard2, shard3。
Config Servers存储集群的元数据。
# 在每个节点上创建配置目录
mkdir -p /data/configdb
# 启动Config Server
mongod --configsvr --replSet configReplSet --dbpath /data/configdb --port 27019 --bind_ip localhost,<node_ip>
在每个节点上执行上述命令,替换<node_ip>为节点的IP地址。
连接到其中一个Config Server并初始化Replica Set。
mongo --port 27019
在mongo shell中执行:
rs.initiate(
{
_id: "configReplSet",
configsvr: true,
members: [
{ _id : 0, host : "shard1_ip:27019" },
{ _id : 1, host : "shard2_ip:27019" },
{ _id : 2, host : "shard3_ip:27019" }
]
}
)
在每个Shard节点上启动MongoDB并配置为Shard Server。
mongod --shardsvr --replSet shardReplSet --dbpath /data/shard1 --port 27018 --bind_ip localhost,<node_ip>
在每个节点上执行上述命令,替换<node_ip>为节点的IP地址,并确保端口号不同。
初始化Shard Replica Set:
mongo --port 27018
在mongo shell中执行:
rs.initiate(
{
_id: "shardReplSet",
members: [
{ _id : 0, host : "shard1_ip:27018" },
{ _id : 1, host : "shard2_ip:27018" },
{ _id : 2, host : "shard3_ip:27018" }
]
}
)
在每个Mongos节点上启动MongoDB并配置为Mongos Router。
mongos --configdb configReplSet/shard1_ip:27019,shard2_ip:27019,shard3_ip:27019 --port 27017 --bind_ip localhost,<node_ip>
在每个节点上执行上述命令,替换<node_ip>为节点的IP地址。
连接到Mongos Router并添加Shards。
mongo --port 27017
在mongo shell中执行:
sh.addShard("shardReplSet/shard1_ip:27018")
sh.addShard("shardReplSet/shard2_ip:27018")
sh.addShard("shardReplSet/shard3_ip:27018")
连接到Mongos Router并启用数据库和集合分片。
sh.enableSharding("yourDatabaseName")
sh.shardCollection("yourDatabaseName.yourCollectionName", { "shardKey": 1 })
连接到Mongos Router并检查集群状态。
sh.status()
为了提高可用性和容错性,你可以为每个Shard配置副本集。
mongod --shardsvr --replSet shardReplSet --dbpath /data/shard1 --port 27018 --bind_ip localhost,<node_ip>
在每个节点上执行上述命令,替换<node_ip>为节点的IP地址,并确保端口号不同。
初始化Shard Replica Set:
mongo --port 27018
在mongo shell中执行:
rs.initiate(
{
_id: "shardReplSet",
members: [
{ _id : 0, host : "shard1_ip:27018" },
{ _id : 1, host : "shard2_ip:27018" },
{ _id : 2, host : "shard3_ip:27018" }
]
}
)
通过以上步骤,你应该能够在CentOS上成功搭建一个MongoDB分片集群。