目录
摘要
分片原理,分片执行过程
分片
概念
- 分片是指将数据拆分,将其分散到不同机器上的过程,即按值的范围进行横向分片
- mongodb 支持自动分片
何时分片
- 磁盘不够用了
- 单个 mongd 不能满足写数据性能要求,想将大量数据放在内存中提高性能
片键
- 片键指从集合中挑选一个键,该键值做为数据拆分的依据
- 片键应该是离散的
服务器分类
- 分片服务器
- 配置服务器
- 路由服务器 mongos 连接到配置服务器,追踪其上面的分片信息
使用
执行过程
不分片时
客户端 -> mongod
分片时
客户端 -> mongos -> mongod1[ mongod2, mongo3… ]
- 客户端发起请求
- mongos 连接到配置服务器获取其上面的分片信息
- mongos 根据请求的信息其分片信息连接到对应的分片服务器上进行查找
建立分片步骤
- 选片键
- 建立并启动分片节点
- 创建并启动配置服务器
- 启动 mongos 路由进程,./mongos –port 指定配置服务器
- 添加分片(登陆到 mongos 上,mongo localhost:30000/admin)
例
第一种
建立db1 db2 config
//建立节点
./mongod -f ../etc/mongo.conf --dbpath=data/db1
./mongod -f ../etc/mongo1.conf --dbpath=data/db2 --port 27018
./mongod -f ../etc/mongo2.conf --port 20000 --dbpath=data/config/
./mongos --port 30000 --configdb localhost:20000
//登录到 mongos 上
//添加到分片
db.runCommand({addshard:"localhost:27017",allowLocal:true})
db.runCommand({addshard:"localhost:27018",allowLocal:true})
//启动分片
db.runCommand({"enablesharding":"chacha"})
//指定片键
db.runCommand({"shardcollection":"chacha.account","key":{"userName":1}})
第二种
//1. 启动作为分片的节点
mongod --shardsvr --dbpath data/mongo4 --port 27014
mongod --shardsvr --dbpath data/mongo5 --port 27015
//2. 创建配置服务器
mongod --configsvr --dbpath data/mongoconfig --port 27016
//3. 创建 mongos 路由进程
mongos --configdb localhost:27016 --chunkSize 1 --port 27020
//4. 添加到分片
mongo localhost:27020/admin
db.runCommand( { addshard : "localhost:27014" })
db.runCommand( { addshard : "localhost:27015" })
//5. 指定分片的数据库
db.runCommand( { enablesharding : "test"})
//6. 指定片键
db.runCommand( { shardcollection : "test.cities", key : {name : 1}})
//导入测试数据
mongoimport -h localhost:27020 --db test --collection cities \ --type json mongo_cities1000.json
片的总记录数即为实际记录数