mongodb分片部署

来源:互联网 发布:七政四余排盘软件下载 编辑:程序博客网 时间:2024/06/05 08:13

本人mongodb版本:MongoDB server version: 3.4.7

一、分片部署的结构

1、分片a(副本集1主1备1仲裁)

2、分片b(副本集1主1备1仲裁)

3、配置集群(副本及1主2备)

4、mongos


二、创建分片a、分片b

(1)创建目录

rs-a-1

rs-a-2

rs-a-3

rs-b-1

rs-b-2

rs-b3

(2)创建分片a

mongod --shardsvr --replSet shard-a --dbpath=rs-a-1 --port 30000 --logpath=rs-a-1.log --nojournalmongod --shardsvr --replSet shard-a --dbpath=rs-a-2 --port 30001 --logpath=rs-a-2.log --nojournalmongod --shardsvr --replSet shard-a --dbpath=rs-a-3 --port 30003 --logpath=rs-a-3.log --nojournal

(3) 创建分片b

mongod --shardsvr --replSet shard-b --dbpath=rs-b-1 --port 30100 --logpath=rs-b-1.log --nojournalmongod --shardsvr --replSet shard-b --dbpath=rs-b-2 --port 30101 --logpath=rs-b-2.log --nojournalmongod --shardsvr --replSet shard-b --dbpath=rs-b-3 --port 30102 --logpath=rs-b-3.log --nojournal


(4)初始化副本集

hostName:主机名或者ip

分片a集群

mongo 127.0.0.1:30000rs.initiate()rs.add("hostName:30001")rs.add("hostName:30002",{arbiterOnly:true})

分片b同理


三、创建配置集群

(1)创建目录

config-1

config-2

config-3

(2)创建配置

mongod --configsvr --replSet conf --dbpath=config-1 --port 27019 --logpath=config-1.log --logappendmongod --configsvr --replSet conf --dbpath=config-2 --port 27020 --logpath=config-2.log --logappendmongod --configsvr --replSet conf --dbpath=config-3 --port 27021 --logpath=config-3.log --logappend

(3)初始化配置副本集

mongo 127.0.0.1:27019rs.initiate()rs.add("hostName:27020")rs.add("hostName:27021")


四、启动mongos

mongos --configdb conf/hostName:27019,hostName:27020,hostName:27021 --logpath=mongos.log --port 40000
mongodb3.4的版本强制配置要设置成副本集,启动mongos时指定配置副本集的名称conf


五、添加分片

先连接mongos

mongo 127.0.0.1:40000


sh.addShard可以用于添加分片,它接受一个字符串,字符串包含副本集名称,随后是两个或多个要连接的种子节点地址。这里你指定两个先前创建的副本集,用的是每个副本集中的非仲裁节点的地址

添加分片a

sh.addShard("shard-a/hostName:30000,lhostName:30001")
添加分片b

sh.addShard("shard-b/hostName:30100,hostName:30101")


添加分片后,可通过

db.getSiblingDB("config").shards.find()
或者

sh.status()
查看


六、开启数据库上的分片

依然是连接mongos,利用sh.enableSharding("dbName")开启数据库的分片,参数是数据库名

sh.enableSharding("dbName")


七、创建集合的分片键

定义分片键,利用sh.shardCollection("dbName.collectionName",key),参数一是数据库的集合,参数二是使用的索引

sh.shardCollection("dbName.user",{_id:1,username:1})

报错:please create an index that starts with the shard key before sharding

参考:https://www.cnblogs.com/lazyboy/archive/2012/11/26/2789401.html

因为user这个表里面根本没有{_id:1,username:1}这个混合索引,先给user表创建混合索引{_id:1,username:1}

use dbNamedb.user.ensureIndex({_id:1,name:1})


再执行
sh.shardCollection("dbName.user",{_id:1,username:1})




原创粉丝点击