MongoDB分片集群部署和监控

一、环境说明

1、各个角色的部署情况

角色 IP 端口 复制集名称
mongos 172.21.244.101,172.21.244.102,172.21.244.94 27000
config server 172.21.244.101,172.21.244.102,172.21.244.94 27100 repl_configsvr
存储节点(shard) 172.21.244.101,172.21.244.102,172.21.244.94 27101 shard1

2、MongoDB版本

mongos> db.version()
4.0.9-12-g7e345a7

二、基础信息准备

1、系统优化

echo "never" >/sys/kernel/mm/transparent_hugepage/enabled
echo "never" >/sys/kernel/mm/transparent_hugepage/defrag

2、下载MongoDB二进制文件

cd /data/app
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.9.tgz
tar -zxvf mongodb-linux-x86_64-4.0.9.tgz

3、相关目录建立

#建立base目录
mkdir /data/mongodb/mongo_db

#把MongoDB二进制文件移动到base目录下的bin文件夹
mv mongodb-4.0.9/bin /data/mongodb/mongo_db/bin

#建立认证文件目录
mkdir /data/mongodb/mongo_db/auth

#建立配置文件目录
mkdir /data/mongodb/mongo_db/conf

#建立config server的data和日志目录
mkdir /data/mongodb/mongo_db/config/data -p
mkdir /data/mongodb/mongo_db/config/log

#建立mongos的日志目录
mkdir /data/mongodb/mongo_db/mongos/log -p

#建立数据节点data和日志目录 
mkdir /data/mongodb/mongo_db/shard1/data -p
mkdir /data/mongodb/mongo_db/shard1/log

3、相关配置文件编写
① mongos的配置文件编写

vim /data/mongodb/mongo_db/conf/mongos.conf
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/mongo_db/mongos/log/mongos.log

processManagement:
  fork: true  # fork and run in background
  pidFilePath: /data/mongodb/mongo_db/mongos/log/mongos.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27000
  bindIpAll: true
  maxIncomingConnections: 1000
  unixDomainSocket:
    enabled: true
    pathPrefix: /data/mongodb/mongo_db/mongos/log
    filePermissions: 0700

security:
  keyFile: /data/mongodb/mongo_db/auth/keyfile.key
#  authorization: enabled

#replication:

sharding:
  configDB: repl_configsvr/172.21.244.101:27100,172.21.244.102:27100,172.21.244.94:27100

② config server的配置文件编写

vim /data/mongodb/mongo_db/conf/config.conf
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/mongo_db/config/log/congigsrv.log

storage:
  dbPath: /data/mongodb/mongo_db/config/data
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      directoryForIndexes: true

processManagement:
  fork: true  # fork and run in background
  pidFilePath: /data/mongodb/mongo_db/config/log/configsrv.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27100
  bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
  #bindIpAll: true
  maxIncomingConnections: 1000
  unixDomainSocket:
    enabled: true
    pathPrefix: /data/mongodb/mongo_db/config/data
    filePermissions: 0700

security:
  keyFile: /data/mongodb/mongo_db/auth/keyfile.key
  authorization: enabled

replication:
  replSetName: repl_configsvr
sharding:
  clusterRole: configsvr

③ 存储节点的配置文件编写

vim /data/mongodb/mongo_db/conf/shard1.conf
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/mongo_db/shard1/log/shard1.log

storage:
  dbPath: /data/mongodb/mongo_db/shard1/data
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      directoryForIndexes: true

processManagement:
  fork: true  # fork and run in background
  pidFilePath: /data/mongodb/mongo_db/shard1/log/shard1.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27101
  bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
  #bindIpAll: true
  maxIncomingConnections: 1000
  unixDomainSocket:
    enabled: true
    pathPrefix: /data/mongodb/mongo_db/shard1/data
    filePermissions: 0700

security:
  keyFile: /data/mongodb/mongo_db/auth/keyfile.key
  authorization: enabled

replication:
  replSetName: shard1
sharding:
  clusterRole: shardsvr

4、key认证文件

echo "chj123456" >/data/mongodb/mongo_db/auth/keyfile.key

#设置文件的权限为400,不然服务无法启动
chmod 400 /data/mongodb/mongo_db/auth/keyfile.key

三、集群初始化

1、启动 config server 服务

/data/mongodb/mongo_db/bin/mongod -f /data/mongodb/mongo_db/conf/config.conf

2、初始化config server集群

#登录其中一个config server节点
/data/mongodb/mongo_db/bin/mongo --port 27100

#配置集群
config = { _id:"repl_configsvr",members:[ {_id:0,host:"172.21.244.101:27100"}, {_id:1,host:"172.21.244.102:27100"}, {_id:2,host:"172.21.244.94:27100"}] }

#初始化集群
> rs.initiate(config)
PS:
结果输出如下,说明集群初始化成功,可以通过 rs.status() 命令查看集群状态
{
        "ok" : 1,
        "$gleStats" : {
                "lastOpTime" : Timestamp(1557538260, 1),
                "electionId" : ObjectId("000000000000000000000000")
        },
        "lastCommittedOpTime" : Timestamp(0, 0)
}

3、启动存储节点服务

/data/mongodb/mongo_db/bin/mongod -f /data/mongodb/mongo_db/conf/shard1.conf

4、初始化存储集群

#登录你希望是主节点的服务器
/data/mongodb/mongo_db/bin/mongo --port 27101

#配置集群
config = { _id:"shard1",members:[ {_id:0,host:"172.21.244.101:27101"}, {_id:1,host:"172.21.244.102:27101"},{_id:2,host:"172.21.244.94:27101",arbiterOnly:true}] }

#初始化集群
> rs.initiate(config)
PS:
结果输出如下,说明集群初始化成功,可以通过rs.status()命令查看集群状态
{ "ok" : 1 }

5、添加存储集群的管理账号

#登录主节点
/data/mongodb/mongo_db/bin/mongo --port 27101
> use admin
> db.createUser(
{
user: "root",
pwd: "123456",
roles: [ { role: "root", db: "admin" } ]
}
)

6、启动mongos 服务

/data/mongodb/mongo_db/bin/mongos -f /data/mongodb/mongo_db/conf/mongos.conf

7、添加config server的管理账号

#登录任意一个mongos节点
/data/mongodb/mongo_db/bin/mongo --port 27000

> use admin
> db.createUser(
{
user: "root",
pwd: "123456",
roles: [ { role: "root", db: "admin" } ]
}
)

8、把存储节点添加到mongos

登录任意一个mongos节点(如果是在上一步的窗口,需要退出重新登录)
/data/mongodb/mongo_db/bin/mongo --port 27000

> use admin
> db.auth('root','123456')

#添加分片
sh.addShard('shard1/172.21.244.101:27101,172.21.244.102:27101,172.21.244.94:27101')

#查看分片状态
sh.status()

四、交付业务方

1、建立应用账号

#登录任意一个mongos节点
/data/mongodb/mongo_db/bin/mongo --port 27000

> use admin
> db.auth('root','123456')

#切到业务数据库
> use chj_db

#建立读写账号
> db.createUser(
{
   user: "chj_db_rw",
   pwd: "123456",
   roles: [
      { role: "readWrite", db: "chj_db" },
      { role: "dbOwner", db: "chj_db" }
   ]
}
)

#建立只读账号(根据业务需求确认是否需要)
> db.createUser(
{
user: "chj_db_r",
pwd: "123456",
roles: [ { role: "read", db: "chj_db" } ]
}
)

2、交付开发人员信息

连接地址:172.21.244.101:27000,172.21.244.102:27000,172.21.244.94:27000
库名:chj_db
账号:chj_db_rw
密码:123456

五、数据库启用分片

如果后期业务量大,需要开启分片,配置如下

#指定需要分片的数据库
mongos> sh.enableSharding("chj_db")  
{
        "ok" : 1,
        "operationTime" : Timestamp(1557546835, 3),
        "$clusterTime" : {
                "clusterTime" : Timestamp(1557546835, 3),
                "signature" : {
                        "hash" : BinData(0,"bkrrr8Kxrr9j9udrDc/hURHld38="),
                        "keyId" : NumberLong("6689575940508352541")
                }
        }
}

#在chj_db数据库和users集合中创建了name和age为升序的片键
mongos> sh.shardCollection("chj_db.users",{name:1,age:1})  
{
        "collectionsharded" : "chj_db.users",
        "collectionUUID" : UUID("59c0b99f-efff-4132-b489-f6c7e3d98f42"),
        "ok" : 1,
        "operationTime" : Timestamp(1557546861, 12),
        "$clusterTime" : {
                "clusterTime" : Timestamp(1557546861, 12),
                "signature" : {
                        "hash" : BinData(0,"UBB1A/YODnmXwG5eAhgNLcKVzug="),
                        "keyId" : NumberLong("6689575940508352541")
                }
        }
}

#查看分片情况
mongos> sh.status()  
--- Sharding Status ---
  sharding version: {
        "_id" : 1,
        "minCompatibleVersion" : 5,
        "currentVersion" : 6,
        "clusterId" : ObjectId("5cd625e0da695346d740f749")
  }
  shards:
        {  "_id" : "shard1",  "host" : "shard1/172.21.244.101:27101,172.21.244.102:27101",  "state" : 1 }
  active mongoses:
        "4.0.4-62-g7e345a7" : 3
  autosplit:
        Currently enabled: yes
  balancer:
        Currently enabled:  yes
        Currently running:  no
        Failed balancer rounds in last 5 attempts:  0
        Migration Results for the last 24 hours:
                No recent migrations
  databases:
        {  "_id" : "chj_db",  "primary" : "shard1",  "partitioned" : true,  "version" : {  "uuid" : UUID("82088bc7-7b98-4033-843d-7058d8d959f6"),  "lastMod" : 1 } }
                chj_db.users
                        shard key: { "name" : 1, "age" : 1 }
                        unique: false
                        balancing: true
                        chunks:
                                shard1  1
                        { "name" : { "$minKey" : 1 }, "age" : { "$minKey" : 1 } } -->> { "name" : { "$maxKey" : 1 }, "age" : { "$maxKey" : 1 } } on : shard1 Timestamp(1, 0)
        {  "_id" : "config",  "primary" : "config",  "partitioned" : true }
                config.system.sessions
                        shard key: { "_id" : 1 }
                        unique: false
                        balancing: true
                        chunks:
                                shard1  1
                        { "_id" : { "$minKey" : 1 } } -->> { "_id" : { "$maxKey" : 1 } } on : shard1 Timestamp(1, 0)

六、MongDB数据库监控

1、mongostat 可用于查看当前QPS/内存使用/连接数,以及多个shard的压力分布

mongostat --port 27000  -u admin -p xxx --authenticationDatabase=admin --discover -n 30 3

参数说明
-discover 提供集群中所有节点的状态
-n 30 3 表示输出30次,每次休眠3秒钟

#扩展(增加mongostat输出列)
mongostat -O 'host,version,network.numRequests=network requests'

输出参数说明:

inserts/s 每秒插入次数
query/s   每秒查询次数
update/s  每秒更新次数
delete/s  每秒删除次数
getmore/s 每秒执行getmore次数
command/s 每秒的命令数,比以上插入、查找、更新、删除的综合还多,还统计了别的命令
flushs/s  每秒执行fsync将数据写入硬盘的次数。
mapped/s  所有的被mmap的数据量,单位是MB,
vsize     虚拟内存使用量,单位MB
res       物理内存使用量,单位MB
faults/s  每秒访问失败数(只有Linux有),数据被交换出物理内存,放到swap。不要超过100,否则就是机器内存太小,造成频繁swap写入。此时要升级内存或者扩展
locked %  被锁的时间百分比,尽量控制在50%以下吧
idx miss %  索引不命中所占百分比。如果太高的话就要考虑索引是不是少了
q t|r|w   当Mongodb接收到太多的命令而数据库被锁住无法执行完成,它会将命令加入队列。这一栏显示了总共、读、写3个队列的长度,都为0的话表示mongo毫无压力。高并发时,一般队列值会升高。
conn      当前连接数
time      时间戳

2、mongotop

mongotop --port 27000  -u admin -p xxx --authenticationDatabase=admin

3、profiler
类似于MySQL的slow log, MongoDB可以监控所有慢的以及不慢的查询。
Profiler默认是关闭的,你可以选择全部开启,或者有慢查询的时候开启

> use test
switched to db test
> db.setProfilingLevel(2);
{ "was" : 0, "slowms" : 100, "sampleRate" : 1, "ok" : 1 }
> db.getProfilingLevel()
2

slowms:代表输出 操作大于100毫秒的语句

设置0代表当前的数据库禁止profiler功能,但是这个Mongo实例下的数据库,只要等级是1的,都会使用20ms的配置

db.setProfilingLevel(0,20)

查看Profile日志

> db.system.profile.find().sort({$natural:-1})
{"ts" : "Thu May 17 2019 12:19:32 GMT-0500 (EST)" , "info" :
"query test.$cmd ntoreturn:1 reslen:66 nscanned:0 query: { profile: 2 } nreturned:1 bytes:50" ,
"millis" : 0} ...

3个字段的意义

ts:时间戳
info:具体的操作
millis:操作所花时间,毫秒

官网地址:https://docs.mongodb.com/manual/tutorial/manage-the-database-profiler/

4、其他

> db.serverStatus()    #详细的Mongo服务器信息
> db.currentOp()       #显示当前的用户操作
> db.stats()           #当前数据库的信息
> db.collection.stats()   #mongo数据库的集合详细信息
> db.printShardingStatus()   #分片状态,或者用  sh.status()

更多详细信息请参考:
https://segmentfault.com/a/1190000011669030
http://www.mongoing.com/docs/administration/monitoring.html

猜你喜欢

转载自blog.csdn.net/m0_37886429/article/details/90290885