NoSQL数据库Mongodb副本集架构(Replica Set)高可用部署

时间:2022-12-26 21:04:56

         NoSQL数据库Mongodb副本集架构(Replica Set)高可用部署

                                         作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

  

  MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

  Mongodb是时下流行的NoSql数据库,它的存储方式是文档式存储,并不是Key-Value形式。关于Mongodb的特点,这里就不多介绍了,大家可以去看看官方说明:https://docs.mongodb.com/manual/。mongodb有几种部署方式(Replica Set / Sharding / Master-Slaver),这里采用的是副本集架构(Replica Set)。这种部署方式也是生成环境经常使用的,如果你对其它的部署方式感兴趣的话大家可以去自行百度。

一.架构介绍

  为了防止单点故障就需要引副本(Replication),当发生硬件故障或者其它原因造成的宕机时,可以使用副本进行恢复,最好能够自动的故障转移(failover)。有时引入副本是为了读写分离,将读的请求分流到副本上,减轻主(Primary)的读压力。而Mongodb的Replica Set都能满足这些要求。

  Replica Set的一堆mongod的实例集合,它们有着同样的数据内容。包含三类角色:

    主节点(Primary):接收所有的写请求,然后把修改同步到所有Secondary。一个Replica Set只能有一个Primary节点,当Primary挂掉后,其他Secondary或者Arbiter节点会重新选举出来一个主节点。默认读请求也是发到Primary节点处理的,需要转发到Secondary需要客户端修改一下连接配置。

    副本节点(Secondary):与主节点保持同样的数据集。当主节点挂掉的时候,参与选主。

    仲裁者(Arbiter):不保有数据,不参与选主,只进行选主投票。使用Arbiter可以减轻数据存储的硬件需求,Arbiter跑起来几乎没什么大的硬件资源需求,但重要的一点是,在生产环境下它和其他数据节点不要部署在同一台机器上。

    注意,一个自动failover的Replica Set节点数必须为奇数,目的是选主投票的时候要有一个大多数才能进行选主决策。

NoSQL数据库Mongodb副本集架构(Replica Set)高可用部署

  由图可以看到客户端连接到整个副本集,不关心具体哪一台机器是否挂掉。主服务器负责整个副本集的读写,副本集定期同步数据备份,一但主节点挂掉,副本节点就会选举一个新的主服务器,这一切对于应用服务器不需要关心。我们看一下主服务器挂掉后的架构:

NoSQL数据库Mongodb副本集架构(Replica Set)高可用部署

  副本集中的副本节点在主节点挂掉后通过心跳机制检测到后,就会在集群内发起主节点的选举机制,自动选举一位新的主服务器。

二.准备环境

1>.操作系统环境

   准备3台配置完全一致的虚拟机(当然IP的配置不能相同!)。内存分配4G即可,主机名需要提前配置好,我的配置环境如下:

NoSQL数据库Mongodb副本集架构(Replica Set)高可用部署

2>.各个主机配置免密登陆(在“node101.yinzhengjie.org.cn”上操作)

[root@node101 ~]# ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
Generating public/private rsa key pair.
Created directory '/root/.ssh'.
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
d1:::b3:ca::0e::f2::::7d::d4: root@node101.yinzhengjie.org.cn
The key's randomart image is:
+--[ RSA ]----+
| ooBo .o+..E|
| .=.B. . o |
| . o + .. . |
| + + o |
| = S |
| + |
| . |
| |
| |
+-----------------+
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# ll ~/.ssh/id_rsa
-rw-------. root root Dec : /root/.ssh/id_rsa
[root@node101 ~]#
[root@node101 ~]# cat ~/.ssh/id_rsa
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAwtFCswPu3AOKXa2TzJRBKG/LC8knCtLE54zMVUaMwbWH0fdV
xHpa8n+V15W3HwLFBZDgyNmnPvZkVJUvTYqf5QaLsxm5J0JAxlmBkY/ayByeULLw
SVIXM/hqBulYnbUViVhGEmBbpI3ASjFVXQyiihyNhzoPZBjdiexnTh7aYJDjQ8qL
IZyQu+rjeoqju839dUmm4RfmqgaPsa717CNxqUgUdviTdK2meV4hA7HtKAxMTpYK
JcEAu3lvh9NRT2k8HSMvEaN/WVUF8SrNN1oUC4aFSO9tDmY3euBCccYf+RqSlzys
m5dxCFDk94cEhsvIzfdzUB4usPs1inUHcQ9pqQIDAQABAoIBAAWbPA4myNLwDyVO
/3fdtFpTjUZTjZoUIrJ/LMovc5GHhdcXBRLYapGb9lXz6wcrbzwPxUhCazu2n4CH
oorauGtA2vhWfyuQDokmvkHQH/2uRSgRXjTd9ej69yInyPMQ6QPA1JNmznxXz/bS
oKBC4tKSq8f+db7tsEJt2TM4VBR/Sg0x77LhZA70MC2+vv+9AoIKVVdZ/KNud+Dk
r2c+Hmo4r7I4G2Oqaj33f7RXFsILIwl0SBvpag4GPhwnOuphXDr3DQ1v5j+4x0rx
3JE+HmlpU66XveUuy7pMurdbOCajwPQgLkDo5W7bBUMIlBS/nZvInncVdDPzWFHO
ZlUh8dkCgYEA6Ykewa0oN96XLPdqbADHRqpzxL7zXJJ644Hh2HygyhR0xw3bOI57
IjkYje9e5PVUcXWuOj/oOMfKal2jW/78bnEgukX1JgkX8RHT9zsgZ0AGEpquHkjv
NrB1qrdbEwnNpSLB8pwGveD9zf89yzocZE+5CUBfnsuAgZqPYkjPMwcCgYEA1Y6x
o1ZxxsPGZIk+hZPuynemdZYnQWp3Z9ynVv902x1/sxcn/uZ+0DZDLQbqGA+2WdEg
EQZ9BwKTCkThoPBJKEzR3Ck122ahqSKCEQRGwK0h05uaA3KSTGIbujGaoBfDWG6f
3fTSWZnTNaObmcOhxTgsMRegy/kWOIgYqdX04c8CgYA9rsf+49uBljtb1yW2zSXV
VmQpjT3+L3ph6QZcBd76QRjvEovajlebnHUN2DG6S8o4BZs1K3gMt0iRe5YQUHMg
QKUiTiQIHdLDC7Bu1qEiZFi2RUDEIwN78HPD2ZYmmypD+cA8clWdhXXEGSybJwgk
vqHi/avD54BTux0wGocPtQKBgFY2Ud4nsqzUMg46HaRdUSQpY2jK4jQVX/js6h1D
6Y/fe8L30SylLoKttTbDONPX2/ysYO6emPCwiF236wJGnrIHOR1RAa3947tc8/cc
q9dyzVoY0fccVJVDcgAbsFl63mCf4CgBgr2rTMm1r8ZGZNMyVxzGdiKB/wd5YcOG
XWKfAoGAYpvjXzEYzr7Y7KKlZBR3gUZZwfngYYgf8g1L42oB1un1NUajiMCyPsm6
oxKrFj6a8SH1xy1U0S7QbPK7osjR5qU7SMsqgziouBl1UmAT5WVKoik4UvHLlKC3
hB0HxUvfVYM5lV3BaggVTC/EOAOsa+jqfbrwjBxjn/kmmv2FtLk=
-----END RSA PRIVATE KEY-----
[root@node101 ~]#
[root@node101 ~]#

[root@node101 ~]# ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa                #生成密钥

[root@node101 ~]# ssh-copy-id root@node101.yinzhengjie.org.cn
The authenticity of host 'node101.yinzhengjie.org.cn (172.30.1.101)' can't be established.
ECDSA key fingerprint is e5::dc::ee:e6:ed::de:::a8:c4:::e7.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@node101.yinzhengjie.org.cn's password: Number of key(s) added: Now try logging into the machine, with: "ssh 'root@node101.yinzhengjie.org.cn'"
and check to make sure that only the key(s) you wanted were added. [root@node101 ~]#
[root@node101 ~]# ssh node101.yinzhengjie.org.cn
Last login: Wed Dec :: from 172.30.1.2
[root@node101 ~]# who
root pts/ -- : (172.30.1.2)
root pts/ -- : (node101.yinzhengjie.org.cn)
[root@node101 ~]#
[root@node101 ~]# logout
Connection to node101.yinzhengjie.org.cn closed.
[root@node101 ~]#

[root@node101 ~]# ssh-copy-id root@node101.yinzhengjie.org.cn              #与本机(node101.yinzhengjie.org.cn)配置免密钥登陆

[root@node101 ~]# ssh-copy-id root@node102.yinzhengjie.org.cn
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@node102.yinzhengjie.org.cn's password: Number of key(s) added: Now try logging into the machine, with: "ssh 'root@node102.yinzhengjie.org.cn'"
and check to make sure that only the key(s) you wanted were added. [root@node101 ~]#
[root@node101 ~]# ssh node102.yinzhengjie.org.cn
Last login: Wed Dec :: from 172.30.1.101
[root@nod102 ~]#
[root@nod102 ~]# who
root pts/ -- : (172.30.1.2)
root pts/ -- : (172.30.1.101)
[root@nod102 ~]#
[root@nod102 ~]# logout
Connection to node102.yinzhengjie.org.cn closed.
[root@node101 ~]#

[root@node101 ~]# ssh-copy-id root@node102.yinzhengjie.org.cn              #与node102.yinzhengjie.org.cn配置免密钥登陆

[root@node101 ~]# ssh-copy-id root@node103.yinzhengjie.org.cn
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@node103.yinzhengjie.org.cn's password: Number of key(s) added: Now try logging into the machine, with: "ssh 'root@node103.yinzhengjie.org.cn'"
and check to make sure that only the key(s) you wanted were added. [root@node101 ~]#
[root@node101 ~]# ssh node103.yinzhengjie.org.cn
Last login: Wed Dec :: from 172.30.1.101
[root@node103 ~]#
[root@node103 ~]#
[root@node103 ~]# who
root pts/ -- : (172.30.1.2)
root pts/ -- : (172.30.1.101)
[root@node103 ~]#
[root@node103 ~]# logout
Connection to node103.yinzhengjie.org.cn closed.
[root@node101 ~]#

[root@node101 ~]# ssh-copy-id root@node103.yinzhengjie.org.cn              #与node103.yinzhengjie.org.cn配置免密钥登陆

3>.编写集群管理脚本

  在配置FQDN和免密钥登陆后,咱们就可以编写一些集群的管理脚本,便于我们下发文件到其他节点中。

[root@node101 ~]# vi /usr/local/bin/xcall.sh              #我们创建该脚本时,直接就把它放在默认的“PATH”环境变量中。因此编辑好后只要有执行权限就可以在任意路径调用它啦!
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# cat /usr/local/bin/xcall.sh
#!/bin/bash
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie
#EMAIL:y1053419035@qq.com #判断用户是否传参
if [ $# -lt ];then
echo "请输入参数"
exit
fi #获取用户输入的命令
cmd=$@ for (( i=;i<=;i++ ))
do
#使终端变绿色
tput setaf
echo ============= node${i}.yinzhengjie.org.cn : $cmd ============
#使终端变回原来的颜色,即白灰色
tput setaf
#远程执行命令
ssh node${i}.yinzhengjie.org.cn $cmd
#判断命令是否执行成功
if [ $? == ];then
echo "命令执行成功"
fi
done
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# chmod +x /usr/local/bin/xcall.sh              #别忘记添加执行权限哟!
[root@node101 ~]#
[root@node101 ~]# xcall.sh cat /etc/redhat-release              #我们在这里可以测试一些咱们的脚本是否好使~
============= node101.yinzhengjie.org.cn : cat /etc/redhat-release ============
CentOS Linux release 7.2. (Core)
命令执行成功
============= node102.yinzhengjie.org.cn : cat /etc/redhat-release ============
CentOS Linux release 7.2. (Core)
命令执行成功
============= node103.yinzhengjie.org.cn : cat /etc/redhat-release ============
CentOS Linux release 7.2. (Core)
命令执行成功
[root@node101 ~]#
[root@node101 ~]#

[root@node101 ~]# vi /usr/local/bin/xcall.sh              #编写批量执行命令的脚本,我们在创建该脚本时,直接就把它放在默认的“PATH”环境变量中。因此编辑好后只要有执行权限就可以在任意路径调用它啦!

[root@node101 ~]# xcall.sh "yum -y install rsync"
============= node101.yinzhengjie.org.cn : yum -y install rsync ============
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.huaweicloud.com
* extras: mirrors.huaweicloud.com
* updates: mirrors..com
Resolving Dependencies
--> Running transaction check
---> Package rsync.x86_64 :3.1.-.el7 will be installed
--> Finished Dependency Resolution Dependencies Resolved ================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
rsync x86_64 3.1.-.el7 base k Transaction Summary
================================================================================
Install Package Total download size: k
Installed size: k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : rsync-3.1.-.el7.x86_64 /
Verifying : rsync-3.1.-.el7.x86_64 / Installed:
rsync.x86_64 :3.1.-.el7 Complete!
命令执行成功
============= node102.yinzhengjie.org.cn : yum -y install rsync ============
Loaded plugins: fastestmirror
Repodata is over weeks old. Install yum-cron? Or run: yum makecache fast
http://mirrors.njupt.edu.cn/centos/7.6.1810/os/x86_64/repodata/bc140c8149fc43a5248fccff0daeef38182e49f6fe75d9b46db1206dc25a6c1c-c7-x86_64-comps.xml.gz: [Errno 12] Timeout on http://10.10.254.10/cache/5/02/mirrors.njupt.edu.cn/033b2636ff3cf3103169fa739764fdd7/bc140c8149fc43a5248fccff0daeef38182e49f6fe75d9b46db1206dc25a6c1c-c7-x86_64-comps.xml.gz: (28, 'Connection timed out after 30682 milliseconds')
Trying other mirror.
http://mirrors.njupt.edu.cn/centos/7.6.1810/updates/x86_64/repodata/8e273c72093a2cfc3f3b2baccfb2b01f7f4bcdc1bb72d53e38074068a756f1c6-primary.sqlite.bz2: [Errno 12] Timeout on http://10.10.254.10/cache/4/02/mirrors.njupt.edu.cn/c35de49cce30395fb97f6c41a56fbad5/8e273c72093a2cfc3f3b2baccfb2b01f7f4bcdc1bb72d53e38074068a756f1c6-primary.sqlite.bz2: (28, 'Connection timed out after 30672 milliseconds')
Trying other mirror.
Determining fastest mirrors
* base: mirrors.huaweicloud.com
* extras: mirrors.huaweicloud.com
* updates: mirrors.neusoft.edu.cn
Resolving Dependencies
--> Running transaction check
---> Package rsync.x86_64 :3.1.-.el7 will be installed
--> Finished Dependency Resolution Dependencies Resolved ================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
rsync x86_64 3.1.-.el7 base k Transaction Summary
================================================================================
Install Package Total download size: k
Installed size: k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : rsync-3.1.-.el7.x86_64 /
Verifying : rsync-3.1.-.el7.x86_64 / Installed:
rsync.x86_64 :3.1.-.el7 Complete!
命令执行成功
============= node103.yinzhengjie.org.cn : yum -y install rsync ============
Loaded plugins: fastestmirror
Repodata is over weeks old. Install yum-cron? Or run: yum makecache fast
http://mirrors.njupt.edu.cn/centos/7.6.1810/os/x86_64/repodata/6614b3605d961a4aaec45d74ac4e5e713e517debb3ee454a1c91097955780697-primary.sqlite.bz2: [Errno 12] Timeout on http://10.10.254.10/cache/5/02/mirrors.njupt.edu.cn/fa6cd86bdbaedbbfedfbfa6d45952cd2/6614b3605d961a4aaec45d74ac4e5e713e517debb3ee454a1c91097955780697-primary.sqlite.bz2: (28, 'Connection timed out after 30867 milliseconds')
Trying other mirror.
Determining fastest mirrors
* base: mirrors.huaweicloud.com
* extras: mirrors.huaweicloud.com
* updates: mirrors.cn99.com
Resolving Dependencies
--> Running transaction check
---> Package rsync.x86_64 :3.1.-.el7 will be installed
--> Finished Dependency Resolution Dependencies Resolved ================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
rsync x86_64 3.1.-.el7 base k Transaction Summary
================================================================================
Install Package Total download size: k
Installed size: k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : rsync-3.1.-.el7.x86_64 /
Verifying : rsync-3.1.-.el7.x86_64 / Installed:
rsync.x86_64 :3.1.-.el7 Complete!
命令执行成功
[root@node101 ~]#

[root@node101 ~]# xcall.sh "yum -y install rsync"            #使用我们上面自定义脚本批量安装rsync服务

[root@node101 ~]# vi /usr/local/bin/xrsync.sh             #编写同步脚本,注意:我们在编写脚本时,就把脚本放在Linux自带的“PATH”环境变量中。
[root@node101 ~]#
[root@node101 ~]# cat /usr/local/bin/xrsync.sh    
#!/bin/bash
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie
#EMAIL:y1053419035@qq.com #判断用户是否传参
if [ $# -lt ];then
echo "请输入参数";
exit
fi #获取文件路径
file=$@ #获取子路径
filename=`basename $file` #获取父路径
dirpath=`dirname $file` #获取完整路径
cd $dirpath
fullpath=`pwd -P` #同步文件到DataNode
for (( i=;i<=;i++ ))
do
#使终端变绿色
tput setaf
echo =========== node${i}.yinzhengjie.org.cn : $file ===========
#使终端变回原来的颜色,即白灰色
tput setaf
#远程执行命令
rsync -lr $filename `whoami`@node${i}.yinzhengjie.org.cn:$fullpath
#判断命令是否执行成功
if [ $? == ];then
echo "命令执行成功"
fi
done
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# chmod +x /usr/local/bin/xrsync.sh          #别忘记添加执行权限哟!
[root@node101 ~]#

[root@node101 ~]# vi /usr/local/bin/xrsync.sh             #编写同步脚本,注意:我们在编写脚本时,就把脚本放在Linux自带的“PATH”环境变量中。

[root@node101 ~]# xcall.sh cat /etc/hosts | grep yinzhengjie                        #我们在没有同步“/etc/hosts”配置文件时,发现只有“node101.yinzhengjie.org.cn”中配置了FQDN
============= node101.yinzhengjie.org.cn : cat /etc/hosts ============
172.30.1.101 node101.yinzhengjie.org.cn
172.30.1.102 node102.yinzhengjie.org.cn
172.30.1.103 node103.yinzhengjie.org.cn
============= node102.yinzhengjie.org.cn : cat /etc/hosts ============
============= node103.yinzhengjie.org.cn : cat /etc/hosts ============
[root@node101 ~]#
[root@node101 ~]# xrsync.sh /etc/hosts                                  #我们利用咱们自定义的脚本将“/etc/hosts”配置文件下发到"node102.yinzhengjie.org.cn"和“node103.yinzhengjie.org.cn”上去。
=========== node102.yinzhengjie.org.cn : /etc/hosts ===========
命令执行成功
=========== node103.yinzhengjie.org.cn : /etc/hosts ===========
命令执行成功
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# xcall.sh cat /etc/hosts | grep yinzhengjie                        #我们验证一下,3台机器上陪孩子是否都相同~如果输出相同说明配置生效啦~
============= node101.yinzhengjie.org.cn : cat /etc/hosts ============
172.30.1.101 node101.yinzhengjie.org.cn
172.30.1.102 node102.yinzhengjie.org.cn
172.30.1.103 node103.yinzhengjie.org.cn
============= node102.yinzhengjie.org.cn : cat /etc/hosts ============
172.30.1.101 node101.yinzhengjie.org.cn
172.30.1.102 node102.yinzhengjie.org.cn
172.30.1.103 node103.yinzhengjie.org.cn
============= node103.yinzhengjie.org.cn : cat /etc/hosts ============
172.30.1.101 node101.yinzhengjie.org.cn
172.30.1.102 node102.yinzhengjie.org.cn
172.30.1.103 node103.yinzhengjie.org.cn
[root@node101 ~]#

4>.关闭防火墙和selinux

[root@node101 java]# xcall.sh systemctl stop firewalld
============= node101.yinzhengjie.org.cn : systemctl stop firewalld ============
命令执行成功
============= node102.yinzhengjie.org.cn : systemctl stop firewalld ============
命令执行成功
============= node103.yinzhengjie.org.cn : systemctl stop firewalld ============
命令执行成功
[root@node101 java]#

[root@node101 java]# xcall.sh systemctl stop firewalld                                #关闭防火墙

[root@node101 java]# xcall.sh systemctl disable firewalld
============= node101.yinzhengjie.org.cn : systemctl disable firewalld ============
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
Removed symlink /etc/systemd/system/basic.target.wants/firewalld.service.
命令执行成功
============= node102.yinzhengjie.org.cn : systemctl disable firewalld ============
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
Removed symlink /etc/systemd/system/basic.target.wants/firewalld.service.
命令执行成功
============= node103.yinzhengjie.org.cn : systemctl disable firewalld ============
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
Removed symlink /etc/systemd/system/basic.target.wants/firewalld.service.
命令执行成功
[root@node101 java]#

[root@node101 java]# xcall.sh systemctl disable firewalld                                #禁用防火墙,防止他开机自启动

[root@node101 java]# xcall.sh systemctl status firewalld
============= node101.yinzhengjie.org.cn : systemctl status firewalld ============
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
Active: inactive (dead) Dec :: node101.yinzhengjie.org.cn systemd[]: Starting firewalld - dynamic firewall daemon...
Dec :: node101.yinzhengjie.org.cn systemd[]: Started firewalld - dynamic firewall daemon.
Dec :: node101.yinzhengjie.org.cn systemd[]: Stopping firewalld - dynamic firewall daemon...
Dec :: node101.yinzhengjie.org.cn systemd[]: Stopped firewalld - dynamic firewall daemon.
============= node102.yinzhengjie.org.cn : systemctl status firewalld ============
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
Active: inactive (dead) Dec :: nod102.yinzhengjie.org.cn systemd[]: Starting firewalld - dynamic firewall daemon...
Dec :: nod102.yinzhengjie.org.cn systemd[]: Started firewalld - dynamic firewall daemon.
Dec :: nod102.yinzhengjie.org.cn systemd[]: Stopping firewalld - dynamic firewall daemon...
Dec :: nod102.yinzhengjie.org.cn systemd[]: Stopped firewalld - dynamic firewall daemon.
============= node103.yinzhengjie.org.cn : systemctl status firewalld ============
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
Active: inactive (dead) Dec :: node103.yinzhengjie.org.cn systemd[]: Starting firewalld - dynamic firewall daemon...
Dec :: node103.yinzhengjie.org.cn systemd[]: Started firewalld - dynamic firewall daemon.
Dec :: node103.yinzhengjie.org.cn systemd[]: Stopping firewalld - dynamic firewall daemon...
Dec :: node103.yinzhengjie.org.cn systemd[]: Stopped firewalld - dynamic firewall daemon.
[root@node101 java]#
[root@node101 java]#
[root@node101 java]#

[root@node101 java]# xcall.sh systemctl status firewalld                                 #查看防火墙状态

[root@node101 ~]# xcall.sh sed -i 's#SELINUX=enforcing#SELINUX=disabled#' /etc/selinux/config
============= node101.yinzhengjie.org.cn : sed -i s#SELINUX=enforcing#SELINUX=disabled# /etc/selinux/config ============
命令执行成功
============= node102.yinzhengjie.org.cn : sed -i s#SELINUX=enforcing#SELINUX=disabled# /etc/selinux/config ============
命令执行成功
============= node103.yinzhengjie.org.cn : sed -i s#SELINUX=enforcing#SELINUX=disabled# /etc/selinux/config ============
命令执行成功
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# xcall.sh cat /etc/selinux/config | grep SELINUX= | grep -v ^#
SELINUX=disabled
SELINUX=disabled
SELINUX=disabled
[root@node101 ~]#

[root@node101 ~]# xcall.sh sed -i 's#SELINUX=enforcing#SELINUX=disabled#' /etc/selinux/config             #禁用selinux,防止它开机自启动,这样修改需要重启操作系统方能生效哦!

[root@node101 ~]# xcall.sh getenforce
============= node101.yinzhengjie.org.cn : getenforce ============
Enforcing
命令执行成功
============= node102.yinzhengjie.org.cn : getenforce ============
Enforcing
命令执行成功
============= node103.yinzhengjie.org.cn : getenforce ============
Enforcing
命令执行成功
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# xcall.sh setenforce
============= node101.yinzhengjie.org.cn : setenforce ============
命令执行成功
============= node102.yinzhengjie.org.cn : setenforce ============
命令执行成功
============= node103.yinzhengjie.org.cn : setenforce ============
命令执行成功
[root@node101 ~]#
[root@node101 ~]# xcall.sh getenforce
============= node101.yinzhengjie.org.cn : getenforce ============
Permissive
命令执行成功
============= node102.yinzhengjie.org.cn : getenforce ============
Permissive
命令执行成功
============= node103.yinzhengjie.org.cn : getenforce ============
Permissive
命令执行成功
[root@node101 ~]#

[root@node101 ~]# xcall.sh setenforce 0                                        #临时关闭selinux,立即生效!

5>.下载Mangodb数据库的软件

[root@node101 ~]# yum -y install wget
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.shu.edu.cn
* extras: mirrors.shu.edu.cn
* updates: mirrors.shu.edu.cn
Resolving Dependencies
--> Running transaction check
---> Package wget.x86_64 :1.14-.el7 will be installed
--> Finished Dependency Resolution Dependencies Resolved =================================================================================================================================================================
Package Arch Version Repository Size
=================================================================================================================================================================
Installing:
wget x86_64 1.14-.el7 base k Transaction Summary
=================================================================================================================================================================
Install Package Total download size: k
Installed size: 2.0 M
Downloading packages:
wget-1.14-.el7.x86_64.rpm | kB ::
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : wget-1.14-.el7.x86_64 /
Verifying : wget-1.14-.el7.x86_64 / Installed:
wget.x86_64 :1.14-.el7 Complete!
[root@node101 ~]#

[root@node101 ~]# yum -y install wget        #安装下载的工具

[root@node101 ~]# wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.4.7.tgz        #下载Mongodb
---- ::-- https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.4.7.tgz
Resolving fastdl.mongodb.org (fastdl.mongodb.org)... 99.84.194.47, 99.84.194.86, 99.84.194.92, ...
Connecting to fastdl.mongodb.org (fastdl.mongodb.org)|99.84.194.47|:... connected.
HTTP request sent, awaiting response... OK
Length: (83M) [application/x-gzip]
Saving to: ‘mongodb-linux-x86_64-3.4..tgz’ %[=======================================================================================================================>] ,, 404KB/s in 3m 33s -- :: ( KB/s) - ‘mongodb-linux-x86_64-3.4..tgz’ saved [/] [root@node101 ~]#

三.安装部署

1>.解压mongodb软件到指定的目录

[root@node101 ~]# mkdir -pv /yinzhengjie/softwares                                  #创建你经常存放目录的位置
mkdir: created directory ‘/yinzhengjie’
mkdir: created directory ‘/yinzhengjie/softwares’
[root@node101 ~]#
[root@node101 ~]# ll
total
-rw-r--r--. root root Aug mongodb-linux-x86_64-3.4..tgz
[root@node101 ~]#
[root@node101 ~]# tar -zxf mongodb-linux-x86_64-3.4..tgz -C /yinzhengjie/softwares/                  #加压mangodb到你指定的目录中去
[root@node101 ~]#
[root@node101 ~]# ln -s /yinzhengjie/softwares/mongodb-linux-x86_64-3.4./ /yinzhengjie/softwares/mongodb      #创建软连接
[root@node101 ~]#
[root@node101 ~]# ll /yinzhengjie/softwares/
total
lrwxrwxrwx. root root Dec : mongodb -> /yinzhengjie/softwares/mongodb-linux-x86_64-3.4./
drwxr-xr-x. root root Dec : mongodb-linux-x86_64-3.4.
[root@node101 ~]#

2>.创建数据目录和日志目录

[root@node101 ~]# cd /yinzhengjie/softwares/mongodb/
[root@node101 mongodb]# ll
total
drwxr-xr-x. root root Dec : bin
-rw-r--r--. root root Aug GNU-AGPL-3.0
-rw-r--r--. root root Aug MPL-
-rw-r--r--. root root Aug README
-rw-r--r--. root root Aug THIRD-PARTY-NOTICES
[root@node101 mongodb]#
[root@node101 mongodb]#
[root@node101 mongodb]# mkdir db logs conf            #创建用于存放数据和日志的目录以及配置文件存放目录
[root@node101 mongodb]#
[root@node101 mongodb]# ll
total
drwxr-xr-x. root root Dec : bin            #存放启动脚本的目录
drwxr-xr-x. root root Dec : conf            #该目录用于存放配置文件
drwxr-xr-x. root root Dec : db             #该目录用于存放数据
-rw-r--r--. root root Aug GNU-AGPL-3.0
drwxr-xr-x. root root Dec : logs            #该目录用于存放日志
-rw-r--r--. root root Aug MPL-
-rw-r--r--. root root Aug README
-rw-r--r--. root root Aug THIRD-PARTY-NOTICES
[root@node101 mongodb]#
[root@node101 mongodb]# pwd
/yinzhengjie/softwares/mongodb
[root@node101 mongodb]#

3>.编辑启动mongodb的配置文件

[root@node101 ~]# cd /yinzhengjie/softwares/mongodb/conf/
[root@node101 conf]#
[root@node101 conf]# vi mongodb.conf
[root@node101 conf]#
[root@node101 conf]# cat mongodb.conf
dbpath=/yinzhengjie/softwares/mongodb/db              #指定数据的存放目录
logpath=/yinzhengjie/softwares/mongodb/logs/mongodb.log      #指定日志的存放目录
port=5200                               #指定mangodb服务的启动端口
fork=true                                #指定是否以守护进程启动mangodb,换句话说就是后台启动,我们这里设置为true。
nohttpinterface=true                          #是否禁止http的接口
[root@node101 conf]#

4>.将mongodb的脚本路径添加到系统环境变量并将“node101.yinzhengjie.org.cn”节点的配置同步到其它节点上去

[root@node101 ~]# vi /etc/profile
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# tail - /etc/profile                      #我们将mongodb的环境变量添加到linux系统的配置文件中
#Add by yinzhengjie
export MONGODB_HOME=/yinzhengjie/softwares/mongodb
export PATH=$PATH:$MONGODB_HOME/bin
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# source /etc/profile
[root@node101 ~]#
[root@node101 ~]# xrsync.sh /etc/profile                      #将数据同步到其它的2个节点上
=========== node102.yinzhengjie.org.cn : /etc/profile ===========
命令执行成功
=========== node103.yinzhengjie.org.cn : /etc/profile ===========
命令执行成功
[root@node101 ~]#
[root@node101 ~]# xcall.sh tail - /etc/profile                    #验证是否同步成功
============= node101.yinzhengjie.org.cn : tail - /etc/profile ============
#Add by yinzhengjie
export MONGODB_HOME=/yinzhengjie/softwares/mongodb
export PATH=$PATH:$MONGODB_HOME/bin
命令执行成功
============= node102.yinzhengjie.org.cn : tail - /etc/profile ============
#Add by yinzhengjie
export MONGODB_HOME=/yinzhengjie/softwares/mongodb
export PATH=$PATH:$MONGODB_HOME/bin
命令执行成功
============= node103.yinzhengjie.org.cn : tail - /etc/profile ============
#Add by yinzhengjie
export MONGODB_HOME=/yinzhengjie/softwares/mongodb
export PATH=$PATH:$MONGODB_HOME/bin
命令执行成功
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# xrsync.sh /yinzhengjie/                  #这一步是必须要做的,否则你在做下一步的时候可能启动不了集群
=========== node102.yinzhengjie.org.cn : /yinzhengjie/ ===========
命令执行成功
=========== node103.yinzhengjie.org.cn : /yinzhengjie/ ===========
命令执行成功
[root@node101 ~]#

5>.编写集群启动脚本

[root@node101 ~]# vi /usr/local/bin/mongodb-start.sh
[root@node101 ~]#
[root@node101 ~]# cat /usr/local/bin/mongodb-start.sh
#!/bin/bash
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie
#EMAIL:y1053419035@qq.com for (( i=;i<=;i++ ));do
ssh node${i}.yinzhengjie.org.cn "source /etc/profile;/yinzhengjie/softwares/mongodb/bin/mongod --replSet repset -f /yinzhengjie/softwares/mongodb/conf/mongodb.conf"
done
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# chmod +x /usr/local/bin/mongodb-start.sh
[root@node101 ~]#

[root@node101 ~]# vi /usr/local/bin/mongodb-start.sh          #做好上一步,咱们就可以编写对应的启动脚本啦!

[root@node101 ~]# mongodb-start.sh                   #启动mongodb集群
about to fork child process, waiting until server is ready for connections.
forked process:
child process started successfully, parent exiting
about to fork child process, waiting until server is ready for connections.
forked process:
child process started successfully, parent exiting
about to fork child process, waiting until server is ready for connections.
forked process:
child process started successfully, parent exiting
[root@node101 ~]#
[root@node101 ~]# xcall.sh ps -ef | grep mongodb | grep -v grep      #这里是检查各个节气是否启动了mongodb服务。
root : ? :: /yinzhengjie/softwares/mongodb/bin/mongod --replSet repset -f /yinzhengjie/softwares/mongodb/conf/mongodb.conf
root : ? :: /yinzhengjie/softwares/mongodb/bin/mongod --replSet repset -f /yinzhengjie/softwares/mongodb/conf/mongodb.conf
root : ? :: /yinzhengjie/softwares/mongodb/bin/mongod --replSet repset -f /yinzhengjie/softwares/mongodb/conf/mongodb.conf
[root@node101 ~]#

6>.初始化副本集群

[root@node101 ~]# yum -y install net-tools
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.shu.edu.cn
* extras: mirrors.shu.edu.cn
* updates: mirrors.shu.edu.cn
Resolving Dependencies
--> Running transaction check
---> Package net-tools.x86_64 :2.0-0.24.20131004git.el7 will be installed
--> Finished Dependency Resolution Dependencies Resolved =================================================================================================================================================================
Package Arch Version Repository Size
=================================================================================================================================================================
Installing:
net-tools x86_64 2.0-0.24.20131004git.el7 base k Transaction Summary
=================================================================================================================================================================
Install Package Total download size: k
Installed size: k
Downloading packages:
net-tools-2.0-0.24.20131004git.el7.x86_64.rpm | kB ::
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : net-tools-2.0-0.24.20131004git.el7.x86_64 /
Verifying : net-tools-2.0-0.24.20131004git.el7.x86_64 / Installed:
net-tools.x86_64 :2.0-0.24.20131004git.el7 Complete!
[root@node101 ~]#

[root@node101 ~]# yum -y install net-tools              #安装网络工具

[root@node101 ~]# ps -ef | grep mongodb | grep -v grep        #检查mongodb进程是否存在,发现进程的pid是9436
root : ? :: /yinzhengjie/softwares/mongodb/bin/mongod --replSet repset -f /yinzhengjie/softwares/mongodb/conf/mongodb.conf
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# netstat -untalp | grep             #我们查看mondb的pid进程是9436,我们可以查看该进程对应的服务端口,发现是咱们设置的5200端口
tcp 0.0.0.0: 0.0.0.0:* LISTEN /mongod
[root@node101 ~]#
[root@node101 ~]# mongo 127.0.0.1:5200              #登录本地的mongodb数据库
MongoDB shell version v3.4.7
connecting to: 127.0.0.1:
MongoDB server version: 3.4.
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
Server has startup warnings:
--22T10::17.974- I CONTROL [initandlisten]
--22T10::17.974- I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
--22T10::17.974- I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
--22T10::17.974- I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
--22T10::17.974- I CONTROL [initandlisten]
--22T10::17.974- I CONTROL [initandlisten]
--22T10::17.974- I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
--22T10::17.974- I CONTROL [initandlisten] ** We suggest setting it to 'never'
--22T10::17.974- I CONTROL [initandlisten]
--22T10::17.974- I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
--22T10::17.974- I CONTROL [initandlisten] ** We suggest setting it to 'never'
--22T10::17.974- I CONTROL [initandlisten]
> config = { _id:"repset", members:[{_id:,host:"node101.yinzhengjie.org.cn:5200"},{_id:,host:"node102.yinzhengjie.org.cn:5200"},{_id:,host:"node103.yinzhengjie.org.cn:5200"}]}
{
"_id" : "repset",
"members" : [
{
"_id" : ,
"host" : "node101.yinzhengjie.org.cn:5200"
},
{
"_id" : ,
"host" : "node102.yinzhengjie.org.cn:5200"
},
{
"_id" : ,
"host" : "node103.yinzhengjie.org.cn:5200"
}
]
}
>
> rs.initiate(config);            #初始化副本集群
{ "ok" : }                 #出现改行提示说明你成功了,注意要关闭防火墙和selinux配置哟,否则你可能还有其它提示信息,比如拒绝连接之类的!
repset:OTHER>
repset:PRIMARY>
repset:PRIMARY>
repset:PRIMARY> rs.status();        #查看集群节点的状态
{
"set" : "repset",
"date" : ISODate("2018-12-22T15:48:53.497Z"),
"myState" : ,
"term" : NumberLong(),
"heartbeatIntervalMillis" : NumberLong(),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(, ),
"t" : NumberLong()
},
"appliedOpTime" : {
"ts" : Timestamp(, ),
"t" : NumberLong()
},
"durableOpTime" : {
"ts" : Timestamp(, ),
"t" : NumberLong()
}
},
"members" : [
{
"_id" : ,
"name" : "node101.yinzhengjie.org.cn:5200",
"health" : ,
"state" : ,
"stateStr" : "PRIMARY",        #这里是节点的状态保存信息!
"uptime" : ,
"optime" : {
"ts" : Timestamp(, ),
"t" : NumberLong()
},
"optimeDate" : ISODate("2018-12-22T15:48:47Z"),
"infoMessage" : "could not find member to sync from",
"electionTime" : Timestamp(, ),
"electionDate" : ISODate("2018-12-22T15:47:45Z"),
"configVersion" : ,
"self" : true
},
{
"_id" : ,
"name" : "node102.yinzhengjie.org.cn:5200",
"health" : ,
"state" : ,
"stateStr" : "SECONDARY",
"uptime" : ,
"optime" : {
"ts" : Timestamp(, ),
"t" : NumberLong()
},
"optimeDurable" : {
"ts" : Timestamp(, ),
"t" : NumberLong()
},
"optimeDate" : ISODate("2018-12-22T15:48:47Z"),
"optimeDurableDate" : ISODate("2018-12-22T15:48:47Z"),
"lastHeartbeat" : ISODate("2018-12-22T15:48:52.040Z"),
"lastHeartbeatRecv" : ISODate("2018-12-22T15:48:52.175Z"),
"pingMs" : NumberLong(),
"syncingTo" : "node101.yinzhengjie.org.cn:5200",
"configVersion" :
},
{
"_id" : ,
"name" : "node103.yinzhengjie.org.cn:5200",
"health" : ,
"state" : ,
"stateStr" : "SECONDARY",
"uptime" : ,
"optime" : {
"ts" : Timestamp(, ),
"t" : NumberLong()
},
"optimeDurable" : {
"ts" : Timestamp(, ),
"t" : NumberLong()
},
"optimeDate" : ISODate("2018-12-22T15:48:47Z"),
"optimeDurableDate" : ISODate("2018-12-22T15:48:47Z"),
"lastHeartbeat" : ISODate("2018-12-22T15:48:52.040Z"),
"lastHeartbeatRecv" : ISODate("2018-12-22T15:48:52.184Z"),
"pingMs" : NumberLong(),
"syncingTo" : "node102.yinzhengjie.org.cn:5200",
"configVersion" :
}
],
"ok" :
}
repset:PRIMARY>         #注意,这里的PRIMARY表示的当前登录的节点是主节点
[root@node102 ~]# mongo 127.0.0.1:
MongoDB shell version v3.4.7
connecting to: 127.0.0.1:
MongoDB server version: 3.4.
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
Server has startup warnings:
--22T10::18.797- I CONTROL [initandlisten]
--22T10::18.798- I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
--22T10::18.798- I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
--22T10::18.798- I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
--22T10::18.798- I CONTROL [initandlisten]
--22T10::18.798- I CONTROL [initandlisten]
--22T10::18.798- I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
--22T10::18.798- I CONTROL [initandlisten] ** We suggest setting it to 'never'
--22T10::18.798- I CONTROL [initandlisten]
--22T10::18.798- I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
--22T10::18.798- I CONTROL [initandlisten] ** We suggest setting it to 'never'
--22T10::18.798- I CONTROL [initandlisten]
repset:SECONDARY>
repset:SECONDARY>         #注意这里的“SECONDRY”表示的是副本节点

[root@node102 ~]# mongo 127.0.0.1:5200          #node102.yinzhengjie.org.cn节点进行测试登录mongodb数据库。注意,如果你不指定端口的默认链接端口是27017!

[root@node103 ~]# mongo 127.0.0.1:
MongoDB shell version v3.4.7
connecting to: 127.0.0.1:
MongoDB server version: 3.4.
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
Server has startup warnings:
--22T10::19.632- I CONTROL [initandlisten]
--22T10::19.632- I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
--22T10::19.632- I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
--22T10::19.632- I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
--22T10::19.632- I CONTROL [initandlisten]
--22T10::19.633- I CONTROL [initandlisten]
--22T10::19.633- I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
--22T10::19.633- I CONTROL [initandlisten] ** We suggest setting it to 'never'
--22T10::19.633- I CONTROL [initandlisten]
--22T10::19.633- I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
--22T10::19.633- I CONTROL [initandlisten] ** We suggest setting it to 'never'
--22T10::19.633- I CONTROL [initandlisten]
repset:SECONDARY>

[root@node103 ~]# mongo 127.0.0.1:5200          #node102.yinzhengjie.org.cn节点进行测试登录mongodb数据库。

 

四.测试集群功能

1>.登录mongodb的主节点并创建“yinzhengjie”数据库。

repset:PRIMARY> use yinzhengjie                      #如果数据库不存在,则创建数据库,否则切换到指定数据库。
switched to db yinzhengjie
repset:PRIMARY>
repset:PRIMARY> db                          #查看当前所在的数据库
yinzhengjie
repset:PRIMARY>
repset:PRIMARY> show databases;                    #查看已经存在的数据库信息
admin .000GB
local .000GB
repset:PRIMARY>
repset:PRIMARY> show dbs                        #除了上面的查看方式,我们也可以通过改命令进行查看
admin .000GB
local .000GB
repset:PRIMARY>
repset:PRIMARY> db.runoob.insert({"job":"DBA"})              #在当前的数据库中创建的runoob表中插入一条数据
WriteResult({ "nInserted" : })
repset:PRIMARY>
repset:PRIMARY> db.runoob.find().pretty();                  #能查看数据当然就能查看相关的数据信息
{ "_id" : ObjectId("5c1e61004f6544b447ca4149"), "job" : "DBA" }
repset:PRIMARY>
repset:PRIMARY>
repset:PRIMARY> show dbs
admin .000GB
local .000GB
yinzhengjie .000GB
repset:PRIMARY>
repset:PRIMARY>
repset:PRIMARY> show databases;
admin .000GB
local .000GB
yinzhengjie .000GB
repset:PRIMARY>

2>.从副本节点连接查看数据

  mongodb默认是从主节点读取数据,副本节点上不允许读,因此我们在查询的时候会抛异常如下:

repset:SECONDARY> show dbs      
--22T11::28.329- E QUERY [thread1] Error: listDatabases failed:{
"ok" : ,
"errmsg" : "not master and slaveOk=false",
"code" : ,
"codeName" : "NotMasterNoSlaveOk"
} :
_getErrorWithCode@src/mongo/shell/utils.js::
Mongo.prototype.getDBs@src/mongo/shell/mongo.js::
shellHelper.show@src/mongo/shell/utils.js::
shellHelper@src/mongo/shell/utils.js::
@(shellhelp2)::
repset:SECONDARY>

  解决方案:

    默认副本节点上不允许读,那么咱们设置副本节点可读即可,在命令执行“db.getMongo().setSlaveOk();”即可,具体操作如下:

repset:SECONDARY> db.getMongo().setSlaveOk();
repset:SECONDARY> show dbs
admin .000GB
local .000GB
yinzhengjie .000GB
repset:SECONDARY>
repset:SECONDARY> use yinzhengjie
switched to db yinzhengjie
repset:SECONDARY> show tables;
runoob
repset:SECONDARY> db.runoob.find().pretty();
{ "_id" : ObjectId("5c1e61004f6544b447ca4149"), "job" : "DBA" }
repset:SECONDARY>
repset:SECONDARY>

3>.测试集群的恢复功能(杀死mongodb主节点存在的进程,观察其它两个节点是否有人结果主节点的角色)

[root@node101 ~]# mongo 127.0.0.1:5200        #当前节点为主节点
MongoDB shell version v3.4.7
connecting to: 127.0.0.1:
MongoDB server version: 3.4.
Server has startup warnings:
--22T10::17.974- I CONTROL [initandlisten]
--22T10::17.974- I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
--22T10::17.974- I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
--22T10::17.974- I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
--22T10::17.974- I CONTROL [initandlisten]
--22T10::17.974- I CONTROL [initandlisten]
--22T10::17.974- I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
--22T10::17.974- I CONTROL [initandlisten] ** We suggest setting it to 'never'
--22T10::17.974- I CONTROL [initandlisten]
--22T10::17.974- I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
--22T10::17.974- I CONTROL [initandlisten] ** We suggest setting it to 'never'
--22T10::17.974- I CONTROL [initandlisten]
repset:PRIMARY> exit
bye
[root@node101 ~]#
[root@node101 ~]# ps -ef | grep mongodb | grep -v grep
root : ? :: /yinzhengjie/softwares/mongodb/bin/mongod --replSet repset -f /yinzhengjie/softwares/mongodb/conf/mongodb.conf
[root@node101 ~]#
[root@node101 ~]# kill - 9436        #杀死主节点的进程
[root@node101 ~]#
[root@node101 ~]#
[root@node101 ~]# mongo 127.0.0.1:5200  #服务没法正常使用了
MongoDB shell version v3.4.7
connecting to: 127.0.0.1:
--22T11::15.645- W NETWORK [thread1] Failed to connect to 127.0.0.1:, in(checking socket for error after poll), reason: Connection refused
--22T11::15.645- E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:5200, connection attempt failed :
connect@src/mongo/shell/mongo.js::
@(connect)::
exception: connect failed
[root@node101 ~]#

  我们发现“node102.yinzhengjie.org.cn”和“node103.yinzhengjie.org.cn”有一个节点立马就接管了主节点的角色

NoSQL数据库Mongodb副本集架构(Replica Set)高可用部署

  当然也是可以在当前节点查看相应的数据的,具体操作如下:

[root@node103 ~]# mongo 127.0.0.1:
MongoDB shell version v3.4.7
connecting to: 127.0.0.1:
MongoDB server version: 3.4.
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
Server has startup warnings:
--22T10::19.632- I CONTROL [initandlisten]
--22T10::19.632- I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
--22T10::19.632- I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
--22T10::19.632- I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
--22T10::19.632- I CONTROL [initandlisten]
--22T10::19.633- I CONTROL [initandlisten]
--22T10::19.633- I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
--22T10::19.633- I CONTROL [initandlisten] ** We suggest setting it to 'never'
--22T10::19.633- I CONTROL [initandlisten]
--22T10::19.633- I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
--22T10::19.633- I CONTROL [initandlisten] ** We suggest setting it to 'never'
--22T10::19.633- I CONTROL [initandlisten]
repset:SECONDARY>
repset:SECONDARY>
repset:SECONDARY>
repset:PRIMARY>
repset:PRIMARY>
repset:PRIMARY> show dbs;
admin .000GB
local .000GB
yinzhengjie .000GB
repset:PRIMARY>
repset:PRIMARY> show tables;
runoob
repset:PRIMARY> db.runoob.find().pretty();
{ "_id" : ObjectId("5c1e61004f6544b447ca4149"), "job" : "DBA" }
repset:PRIMARY>
repset:PRIMARY>
repset:PRIMARY> exit
bye
[root@node103 ~]#

  好啦~同学们,时间也不早了,本次分析就到这里了,如果你想要学习更多关于Mongodb相关的知识,我给大家推荐一个网站,可以系统的帮你学习Mongodb数据库:http://www.runoob.com/mongodb/mongodb-tutorial.html