Mongodb分片 学习小结

前一篇 https://www.cnblogs.com/frx9527/p/mongodb.html 学会搭建复制集Replication之后,就可以学习分片Sharding了。

教程建议看官方文档:https://docs.mongodb.com/manual/ 

总结一下笔记,为了后续速查.

环境准备,安装,不再多述,如有问题查:https://docs.mongodb.com/manual/tutorial/install-mongodb-on-red-hat/

4核8G, CentOS7.6    Mongodb4.2

单机安装测试环境,或者多机安装生产环境,其实仅仅是个主机名(或IP)和端口的区别,

官方建议使用主机名。前提需要做好局域网内DNS解析或者使用统一的hosts文件。

主要是三个部分组成: shard server  ,  config server ,  mongos 

# ------------------------------------ cluster -------------------------
# 单机使用不同端口的方式(测试环境)
cd /data/
tar zxf mongodb-linux-x86_64-rhel70-4.2.0.tgz 
mv mongodb-linux-x86_64-rhel70-4.2.0 mongo4.2.0
cd mongo4.2.0/

# 准备好数据/日志/PID/配置文件 目录
mkdir -p shard conf logs pid
cd shard
mkdir -p rs00 rs01 rs02 rs10 rs11 rs12  
chown -R mongodb:mongodb /data
# 然后切换成mongodb用户操作。

 

先配置config server 使用配置文件/data/mongo4.2.0/conf/conf1.conf:

systemLog:
    path: /data/mongo4.2.0/logs/conf1.log
    logAppend: true
    logRotate: rename
    destination: file

operationProfiling:
  mode: slowOp
  slowOpThresholdMs: 300
  slowOpSampleRate: 1.0

storage:
    dbPath: /data/mongo4.2.0/shard/conf1
    journal:
        enabled: true
    directoryPerDB: true
    engine: wiredTiger
    wiredTiger:
        engineConfig:
            cacheSizeGB: 2
            directoryForIndexes: true

processManagement:
    fork: true
    pidFilePath: /data/mongo4.2.0/pid/conf1.pid

net:
    port: 27100
    bindIpAll: true
    maxIncomingConnections: 16384

security:
    keyFile: /data/mongo4.2.0/conf/ms.key
    authorization: enabled

replication:
    oplogSizeMB: 4096
    replSetName: conf

sharding:
    clusterRole: configsvr
可以使用2个以上节点组成config Server,注意配置文件中要区分不同路径及端口,统一复制集名称。
security 节中提到的 key 文件,单机环境下所有节点可以使用同一个。多机环境下则要保持内容一致。注意权限设成 600
操作:
#------- config server 
# 配置文件 先不启用安全, 注释掉以下三行,为了设置replset账号。
#security:
#    keyFile: /data/mongo4.2.0/conf/conf1.key
#    authorization: enabled

# 启动服务:
sudo ./mongod -f /data/mongo4.2.0/conf/conf1.conf sudo ./mongod -f /data/mongo4.2.0/conf/conf2.conf # 初始化 ./mongo testdb01:27100 >rs.initiate({_id:'conf',members:[{_id:0,host:'testdb01:27100'},{_id:1,host:'testdb01:27101'}]}) # 设置账号密码: > use admin > db.createUser({user: "root", pwd: "123456", roles:[{ role:"root",db:"admin"}]}) > db.auth( "root","123456") # 确认是否正确

 

再配置 shard server   使用配置文件 /data/mongo4.2.0/conf/rs00.conf

systemLog:
    path: /data/mongo4.2.0/logs/rs00.log
    logAppend: true
    logRotate: rename
    destination: file

operationProfiling:
  mode: slowOp
  slowOpThresholdMs: 300
  slowOpSampleRate: 1.0

storage:
    dbPath: /data/mongo4.2.0/shard/rs00
    journal:
        enabled: true
    directoryPerDB: true
    engine: wiredTiger
    wiredTiger:
        engineConfig:
            cacheSizeGB: 3.5
            directoryForIndexes: true

processManagement:
    fork: true
    pidFilePath: /data/mongo4.2.0/pid/rs00.pid

net:
    port: 27000
    bindIpAll: true
    maxIncomingConnections: 16384

security:
    keyFile: /data/mongo4.2.0/conf/ms.key
    authorization: enabled

replication:
    oplogSizeMB: 3300
    replSetName: rs0

sharding:
    clusterRole: shardsvr
2个复制集各配置了3个节点,rs0 三个,rs1 三个。 注意配置文件中要区分不同路径及端口,统一复制集名称。
准备好6个节点的配置文件后,继续操作:
#------- shard server 差不多,仅配置文件稍有不同,先不启用安全。启动服务:
sudo ./mongod -f /data/mongo4.2.0/conf/rs00.conf
sudo ./mongod -f /data/mongo4.2.0/conf/rs01.conf
sudo ./mongod -f /data/mongo4.2.0/conf/rs02.conf
sudo ./mongod -f /data/mongo4.2.0/conf/rs10.conf
sudo ./mongod -f /data/mongo4.2.0/conf/rs11.conf
sudo ./mongod -f /data/mongo4.2.0/conf/rs12.conf

# 初始化 组织2个replset .
/mongo testdb01:27000 >rs.initiate({_id:'rs0',members:[{_id:0,host:'testdb01:27000'},{_id:1,host:'testdb01:27001'},{_id:2,host:'testdb01:27002'}]}) ./mongo testdb01:27010 >rs.initiate({_id:'rs1',members:[{_id:0,host:'testdb01:27010'},{_id:1,host:'testdb01:27011'},{_id:2,host:'testdb01:27012'}]})

# 设置账号密码, 两个replset都要在 primary上设置一次,secondary不用
> use admin > db.createUser({user: "rsroot", pwd: "123456", roles:[{ role:"root",db:"admin"}]}) > db.auth( "rsroot","123456") # 确认是否正确

 

接下来停止所有 mongod 服务( --shutdown),修改配置文件,启用安全配置后,重新启动各项服务.
先启动 config server, 再 shard server。

 

最后配置 mongos 路由服务,使用配置文件 /data/mongo4.2.0/conf/mongos.conf

systemLog:
    path: /data/mongo4.2.0/logs/mongos.log
    logAppend: true
    logRotate: rename
    destination: file

operationProfiling:
#  mode: slowOp
  slowOpThresholdMs: 300
  slowOpSampleRate: 1.0

processManagement:
    fork: true
    pidFilePath: /data/mongo4.2.0/pid/mongos.pid

net:
    port: 27019
    bindIpAll: true
    maxIncomingConnections: 51200

security:
    keyFile: /data/mongo4.2.0/conf/ms.key

sharding:
    configDB: conf/testdb01:27100,testdb01:27101

继续操作:

#------- mongos路由  配置文件不同
sudo ./mongos -f /data/mongo4.2.0/conf/mongos.conf    # 27019
sudo ./mongos -f /data/mongo4.2.0/conf/mongos2.conf   # 27018

# 连接mongos 并添加shard server
.
/mongo testdb01:27019 > use admin > db.auth( "root","123456") >sh.addShard("rs0/testdb01:27000,testdb01:27001,testdb01:27002") >sh.addShard("rs1/testdb01:27010,testdb01:27011,testdb01:27012") # 查看集群状态 > sh.status() # 另一个mongos不必再添加分片设置,因为是连接同一个config server,所以自动与前一个mongos相同 # 如果需要更改密码: > db.changeUserPassword() ##### 如果要停止 mongos 服务, 必须localhost登录shell ./mongo localhost:27019 use admin db.shutdownServer({timeoutSecs: 5}); # 5s shutdown

 

测试 以及 其它命令参考:

# 测试 > 启用指定库分片 > 指定分片key > 插入测试数据
./mongo -u root -p 123456 --authenticationDatabase admin --port 27019
> use admin
#> db.runCommand({enablesharding:"testdb"})  # 库启用分片
#> db.runCommand( { shardcollection : "testdb.users",key : {_id: 1} } )
> sh.enableSharding("testdb")
> sh.shardcollection("testdb.users",{_id: 1})

> use testdb
> for (let i=1; i<100000; i++){db.users.save({name:"user"+i,age:i+1})}  

#> db.runCommand( { shardcollection : "testdb.goods",key : {_id: 1} } )
> sh.shardCollection("testdb.goods", { _id: 1 } )
> use testdb
> for (let i=1; i<100000; i++){db.goods.save({name:"goods"+i,price:i+1,weight:i+2,desc:"test goods"})}
> db.goods.stats()

# 查看集合是否分片:
db.prod_info.stats().sharded



## replset cmd
rs.add()                        # 将成员添加到副本集
rs.addArb()                     # 将仲裁器添加到副本集
rs.conf()                       # 返回副本集配置文档

rs.initiate()                   # 初始化新的副本集
rs.printReplicationInfo()       # 从主数据库的角度打印副本集状态的报告
rs.printSlaveReplicationInfo()  # 从辅助节点的角度打印副本集状态的报告
rs.reconfig()                   # 通过应用新的副本集配置对象重新配置副本集。
rs.remove()                     # 从副本集中删除成员。
rs.slaveOk()                    # 设置slaveOk当前连接的属性。已过时。使用readPref()和Mongo.setReadPref()设置读取首选项。
rs.status()                     # 副本集状态
rs.stepDown()                   # 导致当前的初选成为强制选举的次要。
rs.syncFrom()                   # 设置此副本集成员将同步的成员,覆盖默认同步目标选择逻辑。


## cluster cmd
sh.getBalancerState()           # 当前是否启用了平衡器
sh.status()                     # 分片群集的状态
sh.startBalancer()              # 启用平衡器并等待平衡启动。
sh.stopBalancer()               # 禁用平衡器并等待任何正在进行的平衡完成

sh.addShard()              # 添加一个分片,以分片集群。

sh.disableBalancing()      # 禁用分片数据库中单个集合的平衡。不影响分片集群中其他集合的平衡。
sh.enableBalancing()       # 如果先前已禁用,则激活分片收集平衡器进程sh.disableBalancing()。
sh.disableAutoSplit()      # 禁用分片群集的自动分割
sh.enableAutoSplit()       # 为分片群集启用自动分割
sh.enableSharding()        # 在特定数据库上启用分片

sh.isBalancerRunning()     # 平衡器进程当前是否正在迁移块。
sh.moveChunk()             # 迁移一个块的分片集群

sh.setBalancerState()      # 启用或禁用在分片之间迁移块的平衡器。
sh.shardCollection()       # 集合启用分片
sh.splitAt()               # 使用分片键的特定值作为分割点将现有块分成两个块。
sh.splitFind()             # 将包含与查询匹配的文档的现有块划分为两个近似相等的块。


# 重命名集合,但不能是分片集合。
db.adminCommand({renameCollection:"product_info.prod_inf",to:"product_info.prod_info"}) 

# 刷新所有数据库及其集合的缓存
db.adminCommand("flushRouterConfig")

# 删除当前数据库
db.dropDatabase()

 

 备份恢复参考: 

# database dump
nohup ./mongodump -u root -p 123456 --authenticationDatabase admin -h testdb01:27019 -d A005003 -o /data/dump/ --gzip &

# 不指定集合,则dump所有集合各自独立文件,指定集合则只dump指定集合

# dump specific collection
nohup ./mongodump -u root -p 123456 --authenticationDatabase admin -h testdb01:27019 -d A005001 --collection prod_info -o /data/dump/ --gzip &
## 有gzip选项 体积小很多(缩小近9倍),速度稍慢。无gzip体积巨大,速度稍快。
## dump 的速度比export 要快很多。

nohup ./mongodump -u root -p 123456 --authenticationDatabase admin -h testdb01:27019 -d B002001_otp --collection prod_dup -o /data/dump/ --gzip &
# 结果:Total documents 65.9GB + Total index 272.8MB -->  prod_dup.bson.gz  7,757,486KB
# time: start: 2019-09-06T09:33:37.205 --> end: 2019-09-06T10:02:09.789 约29分钟


# export collection to json file
mongoexport -h testdb01:27019 -u root -p 123456 --authenticationDatabase admin -d A005003 -c prod_ts --type=json -o /data/dump/prod_ts.csv

# export collection to csv file (must fields name)
mongoexport -h testdb01:27019 -u root -p 123456 --authenticationDatabase admin -d A005003 -c prod_ts -f _id,ts,from,via,refid,ProductName,ModuleId,Qr,Opt3,Opt4 --type=csv -o /data/dump/prod_ts.csv

# export limit 10000
mongoexport -h testdb01:27019 -u root -p 123456 --authenticationDatabase admin -d A005003 -c prod_info -f _id,ModuleId,Opt3,Opt4,ProductName,Qr,Profiles,create_ts,profiles_ts --type=csv -o /data/dump/prod_info.csv --limit 10000

# export limit 50000
mongoexport -h testdb01:27019 -u root -p 123456 --authenticationDatabase admin -d A005003 -c prod_info --type=json -o /data/dump/prod_info_50000.json


# 对比 ----------------------------------------------------
prod_info: 9701027rows, documents 796.4GB + index 1.2GB 
prod_ts :  9701026rows, documents 2.1GB + 414.5MB
mongodump begin: 2019-09-05T14:53:33.146
mongodump end :  2019-09-05T22:30:03.238
gz size:  prod_info.bson.gz  134,373,320KB, 
          prod_ts.bson.gz    207,306KB

mongoexport: limit 5M rows, to prod_info_5000000.json 
begin: 2019-09-05T14:46:38.179
end :  2019-09-05T23:26:38.106
file size:  98,530,274KB



#---------------------------------------------------------------------
# 查看bson文件内容
bsondump --pretty /data/dump/A005003nogz/prod_ts.bson 

# 从prod_dup.bson.gz文件恢复 
nohup mongorestore -u root -p 123456 --authenticationDatabase admin -h testdb01:27019 -d A005003 --collection prod_dup --gzip /data/dump/B002001_otp/prod_dup.bson.gz &
# start_time: 2019-09-06T11:12:09.363  --> 100%_time: 2019-09-06T11:23:55.005 --> restore indexes to end: 2019-09-06T11:37:56.806
# 约26分钟 比备份稍快 重建索引花费较多时间

## 问题: 恢复到内存满时,即出错崩溃. 原因是配置文件中cacheSizeGB过大,应该为物理内存的50% 
sudo ./mongorestore -u root -p 123456 --authenticationDatabase admin -h localhost:27111 -d A001001 --gzip /data/mongobak/A005003/prod_info.bson.gz 
./mongorestore  -u root -p 123456 --authenticationDatabase admin -h localhost:27111 -d A001001 --gzip /data/mongobak/B002001_otp/prod_dup.bson.gz

# 指定每个集合并发运行的插入工作器数 4
./mongorestore  -u root -p 123456 --authenticationDatabase admin -h localhost:27111 -d A001001 --gzip /data/mongobak/B002001_otp/prod_dup.bson.gz --numInsertionWorkersPerCollection 4
# 本次恢复prod_dup.bson.gz 大小:7757486KB, 所用时间: 17:00:17 reading metadata --> 17:08:53 restoring indexes --> 17:14:52 done  最终表大小:Doc 65.9 GB + Index 181.9MB,  文档数:1,599,995
# 目标主机:2c 4G  mongodb4.0.10 单机,  cacheSizeGB 2 ,

 

生产环境中,如果遇到需要重启或升级,通常的顺序是:从单个Shard中的某台Secondary开始操作,然后另一台Secondary, 最后操作 Primary. 

线性操作每一个Shard 到完成。然后再依次操作config server. 最后操作mongos

 

登录mongos后,
use config
db.shards.find()     # 查看分片情况
db.databases.find()  # "_id" 数据库名  "partitioned" 是否启用了分片  "primary" 数据在哪个片上
db.chunks.find()     # 查看分块
db.printShardingStatus()  # 概要


 

posted @ 2019-09-08 15:09  枫若雪  阅读(385)  评论(0编辑  收藏  举报