下面以 CentOS 7/8 为例,说明 MongoDB 分片集群(Sharded Cluster) 的基本配置步骤。MongoDB 分片集群通常包含三类角色:
假设 3 台服务器(也可单机多端口模拟):
| 角色 | 主机 | 端口 |
|---|---|---|
| Config Server | 192.168.1.10 | 27019 |
| Shard1 | 192.168.1.11 | 27018 |
| Shard2 | 192.168.1.12 | 27018 |
| Mongos | 192.168.1.10 | 27017 |
生产环境建议:
- Config Server 用 副本集(3节点)
- 每个 Shard 用 副本集
# 以 MongoDB 6.x 为例
cat > /etc/yum.repos.d/mongodb-org.repo <<EOF
[mongodb-org]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/7/mongodb-org/6.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc
EOF
yum install -y mongodb-org
/etc/mongod.confstorage:
dbPath: /var/lib/mongo
journal:
enabled: true
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
port: 27019
bindIp: 0.0.0.0
replication:
replSetName: configReplSet
sharding:
clusterRole: configsvr
systemctl start mongod
systemctl enable mongod
mongosh --port 27019
rs.initiate({
_id: "configReplSet",
configsvr: true,
members: [
{ _id: 0, host: "192.168.1.10:27019" }
]
})
/etc/mongod.confstorage:
dbPath: /var/lib/mongo
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
net:
port: 27018
bindIp: 0.0.0.0
replication:
replSetName: shard1
sharding:
clusterRole: shardsvr
启动并初始化:
systemctl start mongod
mongosh --port 27018
rs.initiate({
_id: "shard1",
members: [
{ _id: 0, host: "192.168.1.11:27018" }
]
})
Shard2 同理(replSetName 改为 shard2)
/etc/mongos.confsystemLog:
destination: file
path: /var/log/mongodb/mongos.log
net:
port: 27017
bindIp: 0.0.0.0
sharding:
configDB: configReplSet/192.168.1.10:27019
mongos -f /etc/mongos.conf
mongosh --port 27017
sh.addShard("shard1/192.168.1.11:27018")
sh.addShard("shard2/192.168.1.12:27018")
查看状态:
sh.status()
sh.enableSharding("testdb")
sh.shardCollection(
"testdb.user",
{ user_id: "hashed" }
)
use testdb
for (let i=0;i<10000;i++){
db.user.insert({user_id:i, name:"user"+i})
}
db.user.getShardDistribution()
如果你需要:
可以直接告诉我你的实际环境。