MongoDB菜鸟入门(二):使用分片和主从副本实行高性能髙可靠数据库

xiaoxiao2021-02-28  126

上一篇简单的记录了一下本人的学习笔记,下面描述的是如何配置分片和主从副本集。

一、分片

由于使用一些传统的数据库(例:mysql等)数据存储量一旦达到某种程度后,查询操作可能会非常耗时,而使用某些内存数据库(例:redis等)则受内存空间大小的限制。而使用mongodb分布式数据库则可以解决此些问题。此处笔记记录了我个人使用了两个分片实践,由于没有更多的机器,此处仅使用单台主机实践。
分片1(shard):
使用端口27001,数据库目录C:\data\shard\s1,日志文件为C:\data\shard\log\s1.log,以追加方式试使用 mongod --port 27001 --dbpath=C:\data\shard\s1 --logpath=C:\data\shard\log\s1.log --logappend
分片2(shard):
使用端口27002,数据库目录C:\data\shard\s2,日志文件为C:\data\shard\log\s2.log,以追加方式试使用 mongod --port 27002 --dbpath=C:\data\shard\s2 --logpath=C:\data\shard\log\s2.log --logappend
Config Server:

配置一个config存储数据库

mongod --port 27100 --dbpath=C:\data\shard\config --logpath=C:\data\shard\log\config.log --logappend --configsvr
Query Routers:

若多config服务器则–configdb后的地址端口列表以逗号隔开

mongos --port 40000 --configdb localhost:27100 --logpath=C:\data\shard\log\route.log --chunkSize 500
最后添加分片shard:

以admin身份登录route路由服务器

//登录route的shell mongo admin --port 40000; //添加分片,若分片有副本等,需用逗号隔开 db.runCommand({addshard:"localhost:27001"}); db.runCommand({addshard:"localhost:27002"}); //选择分片db db.runCommand({enablesharding:"xx"}); //设置xx库user集合分片键 db.runCommand({"shardcollection":"xx.user","key":{"_id":1}})

查看分片服务器配置

db.runCommand( { listshards : 1 } );

二、主从副本

为了实现高可靠的数据库服务器,不至于由于一台服务器挂了使得整个服务不可用,可以使用一主一从、一主多从副本集。副本集的数据是同步的,也就是说数据是一样的,当主机挂了,只要从机还存在,服务就不会中断也不会丢失数据。

主机master:

–replSet指定副本集rs0 mongod --port 27003 --dbpath=C:\data\shard\s3 --logpath=C:\data\shard\log\s3.log --logappend --replSet rs0

从机slave:

–replSet指定副本集rs0 mongod --port 27004 --dbpath=C:\data\shard\s3-slaver --logpath=C:\data\shard\log\s3-slaver.log --logappend --replSet rs0

仲裁机:

仲裁机不存储主从机存储的数据,仅用于在主机挂掉以后,从从机集中选举出新的主机 mongod --port 27005 --dbpath=C:\data\shard\s3-zc --logpath=C:\data\shard\log\s3-zc.log --logappend --replSet rs0

连接主机master:

当master挂掉后,仲裁机会根据投票选举出新的master,启动时priority大者成为master mongo --port 27003 //config设置副本集 config = {_id:"rs0",members:[{_id:0,host:"127.0.0.1:27003",priority:4},{_id:1,host:"127.0.0.1:27004",priority:2},{_id:2,host:"127.0.0.1:27005",arbiterOnly:true}]} //init副本集,使生效 rs.initiate(config)

连接slave:

//连接 mongo --port 27004 //slave需要执行slaveOk才能读取数据 rs.slaveOk()
转载请注明原文地址: https://www.6miu.com/read-18955.html

最新回复(0)