准备相关目录
mongo 分片主要包括三大部分:shard(分片服务器)、mongos(路由服务器) 和 config(配置服务器)
.
└── mongo
├── configdb
│ ├── configsrv1
│ ├── configsrv2
│ └── configsrv3
├── db
│ ├── shard1
│ ├── shard2
│ └── shard3
├── etc
└── logs
shard(分片服务器)配置
每个分片都是整体数据的一部分子集,Mongo 会根据片键均匀的分布到这些子集中去
创建 shard 配置文件
所有的配置文件均放在了 etc
下
配置文件需要准备三份,其中 path
dbPath
pidFilePath
port
replSetName
三份配置文件需要区分开,其他的项可以一致
etc/shard1.conf
systemLog: destination: file logAppend: true path: /data/mongo/logs/shard1.log storage: dbPath: /data/mongo/db/shard1 journal: enabled: true directoryPerDB: true processManagement: fork: true pidFilePath: /data/mongo/db/shard1.pid net: port: 27001 bindIp: 127.0.0.1 replication: replSetName: shard1 sharding: clusterRole: shardsvr
config(配置服务器)配置
配置服务器存储了集群的元数据和配置,必须配置成副本集
创建 config 配置文件
所有的配置文件均放在了 etc
下
配置文件需要准备三份,其中 path
dbPath
pidFilePath
port
三份配置文件需要区分开,其他的项可以一致
etc/configsrv1.conf
systemLog: destination: file logAppend: true path: /data/mongo/logs/configsrv1.log storage: dbPath: /data/mongo/configdb/configsrv1 journal: enabled: true processManagement: fork: true pidFilePath: /data/mongo/configdb/configsrv1.pid net: port: 28001 bindIp: 127.0.0.1 replication: replSetName: mongoconfigs sharding: clusterRole: configsvr
mongos(路由服务器)配置
路由服务器为客户端和分片集群之间提供接口
创建 mongos 配置文件
所有的配置文件均放在了 etc
下
如果需要对外提供访问能力,需要将 bindIp
加上内外网IP,比如需要对内网提供服务,内网 IP 为 172.16.1.100
那么 bindIp
为 127.0.0.1,172.16.1.100
etc/mongos.conf
systemLog: destination: file logAppend: true path: /data/mongo/logs/mongos.log processManagement: fork: true net: port: 27017 bindIp: 127.0.0.1,172.16.1.100 sharding: configDB: mongoconfigs/127.0.0.1:28001,127.0.0.1:28002,127.0.0.1:28003
启动 & 配置
进入到解压缩后 MongoDB
下的 bin
目录
先启动分片服务器和配置服务器
# 启动 配置服务器 ./mongod --config=/data/mongo/etc/configsrv1.conf ./mongod --config=/data/mongo/etc/configsrv2.conf ./mongod --config=/data/mongo/etc/configsrv3.conf # 启动 分片服务器 ./mongod --config=/data/mongo/etc/shard1.conf ./mongod --config=/data/mongo/etc/shard2.conf ./mongod --config=/data/mongo/etc/shard3.conf
配置分片集群
// ./mongo --port 28001 rs.initiate({ _id: "mongoconfigs", configsvr: true, members: [{ _id: 0, host: "127.0.0.1:28001" }, { _id: 1, host: "127.0.0.1:28002" }, { _id: 2, host: "127.0.0.1:28003" }] }) // ./mongo --port 27001 rs.initiate({ _id: "shard1", members: [{ _id: 0, host: "127.0.0.1:27001" }] }) // ./mongo --port 27002 rs.initiate({ _id: "shard2", members: [{ _id: 0, host: "127.0.0.1:27002" }] }) // ./mongo --port 27003 rs.initiate({ _id: "shard3", members: [{ _id: 0, host: "127.0.0.1:27003" }] })
启动 路由服务器
./mongos --config=/data/mongo/etc/mongos.conf
// ./mongo --port 27017 sh.addShard("shard1/127.0.0.1:27001") sh.addShard("shard2/127.0.0.1:27002") sh.addShard("shard3/127.0.0.1:27003") // 查看状态 sh.status()