MongoDB学习笔记10——分片

分片(Sharding)这种技术可以将数据分散到多台机器,但对于应用而言,仍然如同在使用单个数据库一样。在使用MongoDB时,水平分区是唯一可采用的方式。

在MongoDB中由MongoS路径进程管理数据的分割,并将请求路由到必需的分片服务器。

在进行分片的时候需要mongod配置服务器和mongos分片服务器。

1)创建分片设置:

打开新的终端窗口:

$ mkdir -p /db/config/data

$ mongod --port 27022 --dbpath /db/config/data --configsvr --replSet config

$ mongo --port 27022

rs.initiate()

创建分片控制器:

$ mongos --configdb config/<hostname>:27022 --port 27021 --chunkSize 1

启动分片服务器:

$ mkdir -p /db/share0/data

$ mongod --port 27023 --dbpath /db/share0/data

创建一个名为testdb的数据库,然后在数据库中激活一个名为testcollection的集合,对该集合进行分片,赋予它一个名为testkey的参数,作为分片函数:

sh.enableSharing("testdb")

sh.shardCollection("testdb.testcollection",{testkey:1})

验证:

$mongo localhost:27021

use testdb

db.testcollection.count()

在集群中添加新的分片:

$ sudomkdir -p /db/shard2/data

$ sudomongod --port 27025 --dbpath /db/shard2/data

$ mongo localhost:27021

sn.addShard("<hostname>:27025")

在集群中移除分片服务器:

$ mongo localhost:27021

use admin

db.runCommand({removeShard:"<hostname>:27025"})

确定连接的方式:

$ mongo

use testdb

db.runCommand({isdbgrid:1})

isdbgrid:1字段,意味着目前连接到系统中已经启用的分片;如果包含了isdbgrid:0字段,表示连接到mongod。

列出分片服务器的状态:

$ mongo localhost:27021

sh.status()

2)均衡器:

MongoS中包含一个均衡器元素,它将会移动集群中数据的逻辑块,从而保证它们均匀分布在所有分片服务器中。

启动均衡器:

sh.startBalancer()

停止均衡器:

sh.stopBalancer()

 

posted on 2020-03-16 15:33  桌子哥  阅读(184)  评论(0编辑  收藏  举报