Mongodb分片高可用集群搭建

xiaoxiao2021-02-28  114

1.启动三个mongod实例并加入replicate set配置成Config Server服务:

mongod --configsvr --dbpath /usr/local/var/db/config_server/data --replSet mySet --port 30000 mongod --configsvr --dbpath /usr/local/var/db/config_server/data1 --replSet mySet --port 30001 mongod --configsvr --dbpath /usr/local/var/db/config_server/data2 --replSet mySet --port 30002

连接到任意其中一台服务器:

mongo --port 30000

然后执行:

rs.initiate( { _id: "mySet", configsvr: true, members: [ { _id : 0, host : "localhost:30000" }, { _id : 1, host : "localhost:30001" }, { _id : 2, host : "localhost:30002" } ] } )

将三台服务器加入到mySet副本集,同时配置成为config server.

2.启动三个mongod实例并加入replicate set配置成一个Shard Set:

mongod --shardsvr --replSet myShardSet --dbpath /usr/local/var/db/shard/data1/ --port 40001 mongod --shardsvr --replSet myShardSet --dbpath /usr/local/var/db/shard/data2/ --port 40002 mongod --shardsvr --replSet myShardSet --dbpath /usr/local/var/db/shard/data3/ --port 40003

连接到其中任意一台并执行:

rs.initiate( { _id: "myShardSet", configsvr: true, members: [ { _id : 0, host : "localhost:40001" }, { _id : 1, host : "localhost:40002" }, { _id : 2, host : "localhost:40003" } ] } )

3.启动一个mongos

mongos --configdb mySet/localhost:30000,localhost:30001,localhost:30002

默认启动的mongos为端口号:27017

4.将上述配置好的shard set添加到集群中:

连接上述开启的mongos服务:

mongo --port 27017

然后分别执行下面命令:

sh.addShard("myShardSet/localhost:40001"); sh.addShard("myShardSet/localhost:40002"); sh.addShard("myShardSet/localhost:40003");

执行sh.status()可以查看shard是否成功加入到集群

重复第2步操作,创建出另一个shard set,不然我们后面的分片操作都在同一个shard(不同的副本集都是相同的数据),无法展示出分片的效果

sh.addShard("myShardSet2/localhost:50001"); sh.addShard("myShardSet2/localhost:50002"); sh.addShard("myShardSet2/localhost:50003");

5.开启分片配置:

在上述连接好的mongos上:

sh.enableSharding("mytest")

让mytest数据库开启分片,指定的数据库可以之前存在也可以不存在

sh.shardCollection("mytest.student", { "_id" : "hashed" } )

对mytest数据库下的student集合中的_id字段执行hash分片策略 对于shard key也就是上述的_id需要有索引存在,如果集合是空,则开启分片的时候会默认生成index,如果集合事先已经存在,则需要提前手动创建好index

进入到mytest数据库:

use mytest;

插入测试数据:

for(var i=0;i<100;i++){db.student.insert({username:"hello"+i});}

我们加入另一种ranged sharding:

sh.shardCollection( "db.person", { "username":1 } )

插入测试数据:

for(var i=0;i<100;i++){db.person.insert({username:"world"+i});}

最后进入其中一个分片,查看对应的分片后的集合,会发现同一份数据源被分成多分存取在不同shard中,同时有一个replicate set来作一个高可用的保障

转载请注明原文地址: https://www.6miu.com/read-60508.html

最新回复(0)