在CentOS下进行MongoDB数据分片,需要遵循以下步骤:
准备环境: 确保你已经安装了MongoDB,并且所有分片服务器、配置服务器和mongos路由器都已正确配置和运行。
启动配置服务器: 配置服务器存储集群的元数据。在每个配置服务器上运行以下命令:
mongod --configsvr --replSet <configReplSetName> --dbpath <configDbPath> --port <configPort>
将<configReplSetName>替换为配置服务器副本集名称,<configDbPath>替换为配置服务器数据存储路径,<configPort>替换为配置服务器端口(默认为27019)。
mongo --port <configPort>
在mongo shell中输入以下命令:
rs.initiate({
_id: "<configReplSetName>",
configsvr: true,
members: [
{ _id: 0, host: "<configServer1>:<configPort>" },
{ _id: 1, host: "<configServer2>:<configPort>" },
{ _id: 2, host: "<configServer3>:<configPort>" }
]
})
将<configServer1>、<configServer2>和<configServer3>替换为配置服务器的主机名或IP地址。
mongod --shardsvr --replSet <shardReplSetName> --dbpath <shardDbPath> --port <shardPort>
将<shardReplSetName>替换为分片服务器副本集名称,<shardDbPath>替换为分片服务器数据存储路径,<shardPort>替换为分片服务器端口(默认为27018)。
mongo --port <shardPort>
在mongo shell中输入以下命令:
rs.initiate({
_id: "<shardReplSetName>",
shard: true,
members: [
{ _id: 0, host: "<shardServer1>:<shardPort>" },
{ _id: 1, host: "<shardServer2>:<shardPort>" },
{ _id: 2, host: "<shardServer3>:<shardPort>" }
]
})
将<shardServer1>、<shardServer2>和<shardServer3>替换为分片服务器的主机名或IP地址。
mongos --configdb <configReplSetName>/<configServer1>:<configPort>,<configServer2>:<configPort>,<configServer3>:<configPort> --port <mongosPort>
将<configReplSetName>替换为配置服务器副本集名称,<configServer1>、<configServer2>和<configServer3>替换为配置服务器的主机名或IP地址,<mongosPort>替换为mongos路由器端口(默认为27017)。
sh.addShard("<shardReplSetName>/<shardServer1>:<shardPort>,<shardServer2>:<shardPort>,<shardServer3>:<shardPort>")
将<shardReplSetName>替换为分片服务器副本集名称,<shardServer1>、<shardServer2>和<shardServer3>替换为分片服务器的主机名或IP地址。
sh.enableSharding("<database>")
将<database>替换为要分片的数据库名称。
sh.shardCollection("<database>.<collection>", {"<shardKey>": 1})
将<database>替换为数据库名称,<collection>替换为要分片的集合名称,<shardKey>替换为分片键。
完成以上步骤后,MongoDB数据分片将在CentOS环境下成功设置。