Step into MongoDB - 14 - 分片

来源:互联网 发布:提花图案软件 编辑:程序博客网 时间:2024/05/16 15:04

目录

    • 分片
      • 概念
      • 何时分片
      • 片键
        • 服务器分类
      • 使用
        • 执行过程
        • 建立分片步骤

摘要

分片原理,分片执行过程

分片

概念

  • 分片是指将数据拆分,将其分散到不同机器上的过程,即按值的范围进行横向分片
  • 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 27014mongod --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/admindb.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

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

0 0
原创粉丝点击