MongoDB---高级(运维)1 篇
1.分片架构介绍
1.1MongoDB 分片集群特点
• 应用全透明,无特殊处理
• 数据自动均衡
• 动态扩容,无须下线
• 提供三种分片方式
1.2分片集群数据分布方式
分片集群数据分布方式 – 自定义Zone
2.分片集群搭建及扩容
2.1规划
1 2 3 4 5 6 7 8 | 10个实例:38017-38026 (1)configserver: 3台构成的复制集(1主两从,不支持arbiter)38018-38020 (2)shard节点: sh1:38021-23 (1主两从,其中一个节点为arbiter,复制集名字sh1) sh2:38024-26 (1主两从,其中一个节点为arbiter,复制集名字sh2) (3)mongos 38017 |
2.2 配置过程
a. shard复制集配置: 1. 创建: mkdir -p /mongodb/38021/conf /mongodb/38021/log /mongodb/38021/data mkdir -p /mongodb/38022/conf /mongodb/38022/log /mongodb/38022/data mkdir -p /mongodb/38023/conf /mongodb/38023/log /mongodb/38023/data mkdir -p /mongodb/38024/conf /mongodb/38024/log /mongodb/38024/data mkdir -p /mongodb/38025/conf /mongodb/38025/log /mongodb/38025/data mkdir -p /mongodb/38026/conf /mongodb/38026/log /mongodb/38026/data 2. 配置文件: sh1: vi /mongodb/38021/conf/mongodb.conf =============== 根据需求修改相应参数: systemLog: destination: file path: /mongodb/38024/log/mongodb.log logAppend: true storage: journal: enabled: true dbPath: /mongodb/38018/data directoryPerDB: true #engine: wiredTiger wiredTiger: engineConfig: cacheSizeGB: 0.25 directoryForIndexes: true collectionConfig: blockCompressor: zlib indexConfig: prefixCompression: true processManagement: fork: true net: port: 38018 bindIpAll: true replication: oplogSizeMB: 2048 replSetName: sh1 sharding: clusterRole: shardsvr =============== cp /mongodb/38021/conf/mongodb.conf /mongodb/38022/conf/ cp /mongodb/38021/conf/mongodb.conf /mongodb/38023/conf/ sed 's#38021#38022#g' /mongodb/38022/conf/mongodb.conf -i sed 's#38021#38023#g' /mongodb/38023/conf/mongodb.conf -i sh2: vi /mongodb/38024/conf/mongodb.conf ======== 根据需求修改相应参数: systemLog: destination: file path: /mongodb/38024/log/mongodb.log logAppend: true storage: journal: enabled: true dbPath: /mongodb/38024/data directoryPerDB: true #engine: wiredTiger wiredTiger: engineConfig: cacheSizeGB: 0.25 directoryForIndexes: true collectionConfig: blockCompressor: zlib indexConfig: prefixCompression: true processManagement: fork: true net: port: 38024 bindIpAll: true replication: oplogSizeMB: 2048 replSetName: sh2 sharding: clusterRole: shardsvr cp /mongodb/38024/conf/mongodb.conf /mongodb/38025/conf/ cp /mongodb/38024/conf/mongodb.conf /mongodb/38026/conf/ sed 's#38024#38025#g' /mongodb/38025/conf/mongodb.conf -i sed 's#38024#38026#g' /mongodb/38026/conf/mongodb.conf -i 3. 所有节点,并搭建复制集: mongod -f /mongodb/38021/conf/mongodb.conf mongod -f /mongodb/38022/conf/mongodb.conf mongod -f /mongodb/38023/conf/mongodb.conf mongod -f /mongodb/38024/conf/mongodb.conf mongod -f /mongodb/38025/conf/mongodb.conf mongod -f /mongodb/38026/conf/mongodb.conf mongo --port 38021 use admin config = {_id: 'sh1' , members: [ {_id: 0, host: '10.0.0.51:38021' }, {_id: 1, host: '10.0.0.51:38022' }, {_id: 2, host: '10.0.0.51:38023' , "arbiterOnly" : true }] } rs.initiate(config) mongo --port 38024 use admin config = {_id: 'sh2' , members: [ {_id: 0, host: '10.0.0.51:38024' }, {_id: 1, host: '10.0.0.51:38025' }, {_id: 2, host: '10.0.0.51:38026' , "arbiterOnly" : true }] } rs.initiate(config) b.config节点配置: 1. 目录创建: mkdir -p /mongodb/38018/conf /mongodb/38018/log /mongodb/38018/data mkdir -p /mongodb/38019/conf /mongodb/38019/log /mongodb/38019/data mkdir -p /mongodb/38020/conf /mongodb/38020/log /mongodb/38020/data 2. 修改配置文件: [mongod@server1 ~]$ vi /mongodb/38018/conf/mongodb.conf systemLog: destination: file path: /mongodb/38018/log/mongodb.conf logAppend: true storage: journal: enabled: true dbPath: /mongodb/38018/data directoryPerDB: true #engine: wiredTiger wiredTiger: engineConfig: cacheSizeGB: 1 directoryForIndexes: true collectionConfig: blockCompressor: zlib indexConfig: prefixCompression: true net: bindIp: 10.0.0.51,127.0.0.1 port: 38018 replication: oplogSizeMB: 2048 replSetName: configReplSet sharding: clusterRole: configsvr processManagement: fork: true cp /mongodb/38018/conf/mongodb.conf /mongodb/38019/conf/ cp /mongodb/38018/conf/mongodb.conf /mongodb/38020/conf/ sed 's#38018#38019#g' /mongodb/38019/conf/mongodb.conf -i sed 's#38018#38020#g' /mongodb/38020/conf/mongodb.conf -i 3. 启动节点,并配置复制集 mongod -f /mongodb/38018/conf/mongodb.conf mongod -f /mongodb/38019/conf/mongodb.conf mongod -f /mongodb/38020/conf/mongodb.conf mongo --port 38018 use admin config = {_id: 'configReplSet' , members: [ {_id: 0, host: '127.0.0.1:38018' }, {_id: 1, host: '127.0.0.1:38019' }, {_id: 2, host: '127.0.0.1:38020' }] } rs.initiate(config) 注:configserver 可以是一个节点,官方建议复制集。configserver不能有arbiter。 新版本中,要求必须是复制集。 注:mongodb 3.4之后,虽然要求config server为replica set ,但是不支持arbiter c. mongos节点配置: 1. 创建目录: mkdir -p /mongodb/38017/conf /mongodb/38017/log 2配置文件: vi /mongodb/38017/conf/mongos.conf systemLog: destination: file path: /mongodb/38017/log/mongos.log logAppend: true net: bindIp: 127.0.0.1 port: 38017 sharding: configDB: configReplSet/127.0.0.1:38018,127.0.0.1:38019,127.0.0.1:38020 processManagement: fork: true 3. 启动mongos mongos -f /mongodb/38017/conf/mongos.conf d. 分片集群操作: 连接到其中一个mongos(10.0.0.51),做以下配置 (1)连接到mongs的admin数据库 # su - mongod $ mongo 10.0.0.51:38017/admin (2)添加分片 db.runCommand( { addshard : "sh1/127.0.0.1:38021,127.0.0.1:38022,127.0.0.1:38023" , name : "shard1" } ) db.runCommand( { addshard : "sh2/127.0.0.1:38024,127.0.0.1:38025,127.0.0.1:38026" , name : "shard2" } ) (3)列出分片 mongos> db.runCommand( { listshards : 1 } ) (4)整体状态查看 mongos> sh.status(); ================================= e. 使用分片集群 ##RANGE分片配置及测试 test库下的vast大表进行手工分片 1、激活数据库分片功能 mongo --port 38017 admin admin> ( { enablesharding : "数据库名称" } ) eg: admin> db.runCommand( { enablesharding : "test" } ) <br><br>2、指定分片建对集合分片 eg:范围片键 --创建索引 use test > db.vast.ensureIndex( { id: 1 } ) --开启分片 use admin > db.runCommand( { shardcollection : "test.vast" , key : {id: 1} } ) 3、集合分片验证 admin> use test test> for (i=1;i<500000;i++){ db.vast. insert ({ "id" :i, "name" : "shenzheng" , "age" :70, "date" :new Date ()}); } test> db.vast.stats() 4、分片结果测试 shard1: mongo --port 38021 db.vast. count (); shard2: mongo --port 38024 db.vast. count (); ---------------------------------------------------- f. Hash分片例子: 对test库下的vast大表进行hash 创建哈希索引 (1)对于test开启分片功能 mongo --port 38017 admin use admin admin> db.runCommand( { enablesharding : "test" } ) (2)对于test库下的vast表建立hash索引 use test test> db.vast.ensureIndex( { id: "hashed" } ) (3)开启分片 use admin admin > sh.shardCollection( "test.vast" , { id: "hashed" } ) (4)录入10w行数据测试 use test for (i=1;i<100000;i++){ db.vast. insert ({ "id" :i, "name" : "shenzheng" , "age" :70, "date" :new Date ()}); } (5)hash分片结果测试 mongo --port 38021 use test db.vast. count (); mongo --port 38024 use test db.vast. count (); g. 分片的管理 1、查看分片的详细信息 admin> db.printShardingStatus() 或 admin> sh.status() 2、删除分片节点(谨慎) (1)确认blance是否在工作 sh.getBalancerState() (2)删除shard2节点(谨慎) mongos> db.runCommand( { removeShard: "shard2" } ) 注意:删除操作一定会立即触发blancer。 3、balancer操作 介绍: mongos的一个重要功能,自动巡查所有shard节点上的chunk的情况,自动做chunk迁移。 什么时候工作? 1、自动运行,会检测系统不繁忙的时候做迁移 2、在做节点删除的时候,立即开始迁移工作 3、balancer只能在预设定的时间窗口内运行 有需要时可以关闭和开启blancer(备份的时候) mongos> sh.stopBalancer() mongos> sh.startBalancer() 4、自定义 自动平衡进行的时间段 https://docs.mongodb.com/manual/tutorial/manage-sharded-clusterbalancer/#schedule-the-balancing-window // connect to mongos use config sh.setBalancerState( true ) db.settings. update ({ _id : "balancer" }, { $ set : { activeWindow : { start : "3:00" , stop : "5:00" } } }, true ) sh.getBalancerWindow() sh.status()【3点到5点开启balance】 |
---------------------范围分片-----------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // 启动分片服务 sh.enableSharding( "database_name" ); // 为集合指定分片键和范围 sh.shardCollection( "database_name.collection_name" , { "userId" : 1}, { key: { "userId" : 1 }, unique: false , numInitialChunks: 10, bounds: { "userId" : { "min" : 0, "max" : 10000000000, "minIsOpen" : false , "maxIsOpen" : false } } }); |
2.企业中分片集群设计
2.1分片的基本标准
1 2 3 4 | • 关于数据:数据量不超过3TB,尽可能保持在2TB一个片; • 关于索引:常用索引必须容纳进内存; • 按照以上标准初步确定分片后,还需要考虑业务压力,随着压力增大,CPU、RAM、磁盘中的任何一项 出现瓶颈时,都可以通过添加更多分片来解决。 |
2.2 如何粗略判断需要多少分片
2.3 选择片键的正确姿势
3.高级集群设计:两地三中心
3.1 容灾级别
3.2 MongoDB 两地三中心集群实现
3.3 两地三中心规划及实施
b. 两地三中心定制化配置
1 2 3 4 5 | cfg = rs.conf() cfg.members[1].priority = 20 cfg.members[2].priority = 10 cfg.members[3].priority = 10 rs.reconfig(cfg) |
c. 复制集安全加固
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | # db01 openssl rand -base64 756 > /mongodb/10001/conf/keyfile cp -a /mongodb/10001/conf/keyfile /mongodb/10002/conf chmod 600 /mongodb/10001/conf/keyfile /mongodb/10002/conf/keyfile scp /mongodb/10001/conf/keyfile 10.0.0.52:/mongodb/10003/conf scp /mongodb/10001/conf/keyfile 10.0.0.52:/mongodb/10004/conf scp /mongodb/10001/conf/keyfile 10.0.53:/mongodb/10005/conf 每个节点开启验证: cat >> /mongodb/10001/conf/mongod.conf<<EOF security: keyFile: /mongodb/10001/conf/keyfile EOF cat >>/mongodb/10002/conf/mongod.conf<<EOF security: keyFile: /mongodb/10002/conf/keyfile EOF cat >> /mongodb/10003/conf/mongod.conf <<EOF security: keyFile: /mongodb/10003/conf/keyfile EOF cat >> /mongodb/10004/conf/mongod.conf <<EOF security: keyFile: /mongodb/10004/conf/keyfile EOF cat >> /mongodb/10005/conf/mongod.conf <<EOF security: keyFile: /mongodb/10005/conf/keyfile EOF use admin db.shutdownServer() +++++ Shut down each mongod in the replica set , starting with the secondaries. Continue until all members of the replica set are offline, including any arbiters. The primary must be the last member shut down to avoid potential rollbacks. +++++ 启动所有节点,在主节点添加用户: use admin db.createUser( { user : "root" , pwd: "root123" , roles: [ { role: "root" , db: "admin" } ] } ) 手工交互式输入密码 db.createUser( { user : "root1" , pwd: passwordPrompt(), roles: [ { role: "root" , db: "admin" } ] } ) 手工交互式验证 my_repl: PRIMARY > use admin switched to db admin my_repl: PRIMARY > db.auth( "root1" ,passwordPrompt()) Enter password : |
4.MongoDB 备份与恢复及迁移
4.1备份恢复工具介绍:
1 2 | (1)** mongoexport/mongoimport (2)***** mongodump/mongorestore |
4.2 备份工具区别在哪里?
1 2 3 4 5 6 7 8 | mongoexport/mongoimport 导入/导出的是JSON格式或者CSV格式, mongodump/mongorestore导入/导出的是BSON格式。 应用场景: mongoexport/mongoimport:json csv 1、异构平台迁移 mysql < ---> mongodb 2、同平台,跨大版本:mongodb 2 ----> mongodb 3 mongodump/mongorestore 日常备份恢复时使用. |
4.3 导出工具mongoexport
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | Mongodb中的mongoexport工具可以把一个collection导出成JSON格式或CSV格式的文件。 可以通过参数指定导出的数据项,也可以根据指定的条件导出数据。 (1)版本差异较大 (2)异构平台数据迁移 mongoexport具体用法如下所示: $ mongoexport --help 参数说明: -h:指明数据库宿主机的IP -u:指明数据库的用户名 -p:指明数据库的密码 -d:指明数据库的名字 -c:指明collection的名字 -f:指明要导出那些列 -o:指明到要导出的文件名 -q:指明导出数据的过滤条件 --authenticationDatabase admin 1.单表备份至json格式 use test for (i=0;i<10000;i++){ db.log. insert ({ "uid" :i, "name" : "mongodb" , "age" :6, "date" :new Date ()}); } mongoexport -uroot -proot123 --port 27017 --authenticationDatabase admin -d test -c log -o /mongodb/log.json 注:备份文件的名字可以自定义,默认导出了JSON格式的数据。 2. 单表备份至csv格式 如果我们需要导出CSV格式的数据,则需要使用 --type=csv参数: mongoexport -uroot -proot123 --port 27017 --authenticationDatabase admin -d test -c log --type=csv -f uid,name,age,date -o /mongodb/log.csv |
4.4 导入工具mongoimport
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | Mongodb中的mongoimport工具可以把一个特定格式文件中的内容导入到指定的collection中。该 工具可以导入JSON格式数据,也可以导入CSV格式数据。具体使用如下所示: $ mongoimport --help 参数说明: -h:指明数据库宿主机的IP -u:指明数据库的用户名 -p:指明数据库的密码 -d:指明数据库的名字 -c:指明collection的名字 -f:指明要导入那些列 -j, --numInsertionWorkers=<number> number of insert operations to run concurrently (defaults to 1) //并行 数据恢复: 1.恢复json格式表数据到log1 mongoimport -uroot -proot123 --port 27017 --authenticationDatabase admin -d test -c log1 /mongodb/log.json 2.恢复csv格式的文件到log2 上面演示的是导入JSON格式的文件中的内容,如果要导入CSV格式文件中的内容,则需要通过 --type 参数指定导入格式,具体如下所示: 错误的恢复 注意: (1)csv格式的文件头行,有列名字 mongoimport -uroot -proot123 --port 27017 --authenticationDatabase admin -d test -c log2 --type=csv --headerline --file /mongodb/log.csv (2)csv格式的文件头行,没有列名字 mongoimport -uroot -proot123 --port 27017 --authenticationDatabase admin -d test -c log3 -j 4 --type=csv -f id,name,age,date --file /mongodb/log.csv --headerline:指明第一行是列名,不需要导入。 3. 异构平台迁移案例 mysql -----> mongodb world数据库下city表进行导出,导入到mongodb (1)mysql开启安全路径 vim /etc/my.cnf --->添加以下配置 secure-file-priv=/data/backup/ --重启数据库生效 /etc/init.d/mysqld restart (2)导出mysql的city表数据 select * from test.t100w into outfile '/tmp/t100w.csv' fields terminated by ',' ENCLOSED BY '"' ; (3)获取列信息 mysql> select table_name,group_concat(column_name) from information_schema.columns where table_schema= 'test' group by table_name order by null ; + ------------+---------------------------+ | TABLE_NAME | group_concat(column_name) | + ------------+---------------------------+ | t100w | dt,id,k1,k2,num | + ------------+---------------------------+ 1 row in set (0.07 sec) (4)在mongodb中导入备份 mongoimport -uroot -proot123 --port 27017 --authenticationDatabase admin -d test -c t100w --type=csv -f id,num,k1,k2,,dt --file /tmp/t100w.csv use world db.t100w.find({}); 4. 彩蛋————如何将MySQL大量表迁移到MongoDB 痛点: (1) 批量从MySQL导出多张表 mysqldump --fields-terminated-by ',' --fields-enclosed-by '"' world -T /tmp/ cd /data/backup rm -rf /data/backup/*.sql find ./ - name "*.txt" | awk -F "." '{print $2}' | xargs -i -t mv ./{}.txt ./{}.csv (2) 拼接语句 select concat( "mongoimport -uroot -proot123 --port 27017 -- authenticationDatabase admin -d " ,table_schema, " -c " ,table_name , " -- type=csv " , " -f " , group_concat(column_name) , " --file /data/backup/" ,table_name , ".csv" ) from information_schema.columns where table_schema= 'world' group by table_name; (3) 导入数据 [mongod@db01 backup]$ ll total 256 -rwxrwxrwx 1 mysql mysql 184355 Jul 22 13:45 city.csv -rwxrwxrwx 1 mysql mysql 38659 Jul 22 13:45 country.csv -rwxrwxrwx 1 mysql mysql 26106 Jul 22 13:45 countrylanguage.csv -rwxrwxrwx 1 mysql mysql 656 Jul 22 13:45 import.sh [mongod@db01 backup]$ sh import.sh |
4.5 mongodump和mongorestore 备份(二进制的json)
a. mongodump参数
1 2 3 4 5 6 7 8 9 10 11 12 | $ mongodump --help 参数说明: -h:指明数据库宿主机的IP -u:指明数据库的用户名 -p:指明数据库的密码 -d:指明数据库的名字 -c:指明collection的名字 -o:指明到要导出的文件名 -q:指明导出数据的过滤条件 -j, --numParallelCollections= number of collections to dump in parallel (4 by default ) --oplog 备份的同时备份oplog |
b. mongodump和mongorestore基本使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 全库备份 mkdir /mongodb/backup -p mongodump -uroot -proot123 --port 27017 --authenticationDatabase admin -o /mongodb/backup --备份world库 $ mongodump -uroot -proot123 --port 27017 --authenticationDatabase admin -d test -o /mongodb/backup/ --备份test库下的log集合 $ mongodump -uroot -proot123 --port 27017 --authenticationDatabase admin -d test -c log -o /mongodb/backup/ --压缩备份 $ mongodump -uroot -proot123 --port 27017 --authenticationDatabase admin -d abc -o /mongodb/backup/ --gzip mongodump -uroot -proot123 --port 27017 --authenticationDatabase admin - o /mongodb/backup/ --gzip $ mongodump -uroot -proot123 --port 27017 --authenticationDatabase admin -d app -c vast -o /mongodb/backup/ --gzip --全备中恢复单库 $ mongorestore -uroot -proot123 --port 27017 --authenticationDatabase admin -d world1 /mongodb/backup/world --全备中恢复单表 [mongod@db01 backup]$ mongorestore -uroot -proot123 --port 27017 -- authenticationDatabase admin -d a -c t1 /mongodb/backup/world/t5.bson.gz --gzip --drop表示恢复的时候把之前的集合drop掉(危险) $ mongorestore -uroot -proot123 --port 27017 --authenticationDatabase admin -d test --drop /mongodb/backup/test |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~