Step into MongoDB - 14 - 分片

目录

摘要

分片原理,分片执行过程

分片

概念

  • 分片是指将数据拆分,将其分散到不同机器上的过程,即按值的范围进行横向分片
  • mongodb 支持自动分片

何时分片

  • 磁盘不够用了
  • 单个 mongd 不能满足写数据性能要求,想将大量数据放在内存中提高性能

片键

  • 片键指从集合中挑选一个键,该键值做为数据拆分的依据
  • 片键应该是离散的
服务器分类
  • 分片服务器
  • 配置服务器
  • 路由服务器 mongos 连接到配置服务器,追踪其上面的分片信息

使用

执行过程

不分片时

客户端 -> mongod

分片时

客户端 -> mongos -> mongod1[ mongod2, mongo3… ]

  1. 客户端发起请求
  2. mongos 连接到配置服务器获取其上面的分片信息
  3. mongos 根据请求的信息其分片信息连接到对应的分片服务器上进行查找
建立分片步骤
  1. 选片键
  2. 建立并启动分片节点
  3. 创建并启动配置服务器
  4. 启动 mongos 路由进程,./mongos –port 指定配置服务器
  5. 添加分片(登陆到 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

片的总记录数即为实际记录数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值