MongoDB 复制集 & 分片
时间: 2025-05-25 18:07:04 浏览: 50
### MongoDB 复制集与分片的配置及使用指南
#### 一、复制集(Replica Set)
MongoDB 的复制集是一种高可用性和数据冗余机制,它通过多个节点之间的同步来保障数据的安全性。
- **定义**
复制集由一组 mongod 实例组成,其中一个为主节点(Primary),其余为从节点(Secondary)。主节点负责所有的写操作,而从节点则定期从主节点拉取日志并应用到本地副本[^1]。
- **配置步骤**
配置复制集通常涉及以下几个方面:
- 安装和启动 MongoDB 实例。假设我们有三个实例分别运行在 `localhost` 上的不同端口:27017, 27018 和 27019。
```bash
mkdir -p /data/rs0 /data/rs1 /data/rs2
mongod --replSet rs0 --port 27017 --dbpath /data/rs0 --bind_ip localhost &
mongod --replSet rs0 --port 27018 --dbpath /data/rs1 --bind_ip localhost &
mongod --replSet rs0 --port 27019 --dbpath /data/rs2 --bind_ip localhost &
```
- 初始化复制集。连接至任意一个成员并通过 shell 执行初始化命令:
```javascript
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "localhost:27017" },
{ _id: 1, host: "localhost:27018" },
{ _id: 2, host: "localhost:27019", arbiterOnly: true } // 可选仲裁者
]
});
```
- 查看状态以确认配置成功与否:
```javascript
rs.status();
```
#### 二、分片(Sharding)
分片用于水平扩展 MongoDB 数据库的能力,允许将大型集合分布在多个服务器上。
- **基本概念**
分片的核心组件包括路由器(mongos)、配置服务器以及实际存储数据的分片节点。其中,路由服务接收客户端请求并将查询转发给合适的分片;配置服务器保存元数据信息;分片则是具体的数据承载单元[^1]。
- **设置流程**
- 启动必要的进程和服务。这里需要至少两个 shard 节点加上独立的 config server 进程组。
```bash
# Config Server Setup (Single Node Example)
mongod --configsvr --replSet config-rs --dbpath /data/config --port 27019 &
# Shard Servers Initialization
mongod --shardsvr --replSet shard-rs0 --dbpath /data/shard0a --port 27017 &
mongod --shardsvr --replSet shard-rs0 --dbpath /data/shard0b --port 27018 &
# Router Service Activation
mongos --configdb config-rs/localhost:27019 --port 27020 &
```
- 添加 shards 并启用 sharding 功能于目标 namespace 下面。
```javascript
use admin;
db.runCommand({ addShard : "shard-rs0/localhost:27017,localhost:27018" });
db.enableSharding("test"); // 替换 test 为目标 database 名字
db.runCommand({ shardCollection : "test.collectionName", key : { fieldToDistributeOn : 1 } });
```
#### 总结
以上介绍了如何搭建基础版的 MongoDB 复制集环境及其简单的分片架构部署方式。需要注意的是,在生产环境中还需要考虑更多的安全措施如认证授权、SSL 加密通信等额外配置项[^1]。
阅读全文
相关推荐

















