在CentOS上配置MongoDB的分片(Sharding)涉及多个步骤,包括设置配置服务器(Config Servers)、分片服务器(Shard Servers)以及mongos路由器。以下是一个基本的指南:
首先,确保你已经在所有服务器上安装了MongoDB。你可以从MongoDB官方网站下载并安装适合CentOS的MongoDB版本。
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
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
sudo apt-get install -y mongodb-org
配置服务器存储集群的元数据。你需要至少三个配置服务器来保证高可用性。
在每个配置服务器上,编辑/etc/mongod.conf
文件,添加或修改以下内容:
sharding:
clusterRole: configsvr
net:
bindIp: <config_server_ip>
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
然后启动配置服务器:
sudo systemctl start mongod
sudo systemctl enable mongod
连接到其中一个配置服务器并初始化副本集:
mongo --host <config_server_ip>:27019
在mongo shell中执行以下命令:
rs.initiate(
{
_id: "configReplSet",
configsvr: true,
members: [
{ _id : 0, host : "<config_server_ip>:27019" }
]
}
)
重复以上步骤,为其他配置服务器添加成员。
分片服务器存储实际的数据。你需要至少两个分片服务器来保证高可用性。
在每个分片服务器上,编辑/etc/mongod.conf
文件,添加或修改以下内容:
sharding:
clusterRole: shardsvr
net:
bindIp: <shard_server_ip>
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
然后启动分片服务器:
sudo systemctl start mongod
sudo systemctl enable mongod
连接到其中一个分片服务器并初始化副本集:
mongo --host <shard_server_ip>:27018
在mongo shell中执行以下命令:
rs.initiate(
{
_id: "<shard_name>",
members: [
{ _id : 0, host : "<shard_server_ip>:27018" }
]
}
)
重复以上步骤,为其他分片服务器添加成员。
mongos是MongoDB的分片路由器,客户端通过它连接到分片集群。
在mongos服务器上,编辑/etc/mongos.conf
文件,添加或修改以下内容:
sharding:
configDB: configReplSet/<config_server_ip>:27019,<config_server_ip>:27019,<config_server_ip>:27019
net:
bindIp: <mongos_server_ip>
然后启动mongos:
sudo systemctl start mongos
sudo systemctl enable mongos
连接到mongos并添加分片:
mongo --host <mongos_server_ip>:27017
在mongo shell中执行以下命令:
sh.addShard("<shard_name>/<shard_server_ip>:27018")
重复以上步骤,为其他分片添加成员。
连接到mongos并启用数据库和集合的分片:
sh.enableSharding("<database_name>")
sh.shardCollection("<database_name>.<collection_name>", { <shard_key>: "hashed" })
连接到mongos并验证分片配置:
sh.status()
通过以上步骤,你应该能够在CentOS上成功配置MongoDB的分片。请根据你的实际需求调整配置。