数据库
首页 > 数据库> > MongoDB高可用方案之副本集(PSS)的项目实践三

MongoDB高可用方案之副本集(PSS)的项目实践三

作者:互联网

文章目录

第1章 基本环境和基本优化

1.1 准备的服务器

主机名IP地址操作系统角色
vm7-201.host.com10.4.7.201/24CentOS 7.9primary 优先级10,初始化时让其成为主(在这个节点上进行初始化),宕服恢复后不抢占主;
vm7-202.host.com10.4.7.202/24CentOS 7.9secondary 优先级9,有机会参与new primary的选举,优先成为new primary
vm7-203.host.com10.4.7.203/24CentOS 7.9secondary 优先级8,有机会参与new primary的选举;

1.2 项目实践架构

三个节点的优先级都不一样,在初始化时不管在哪个节点上进行操作,vm7-201上的mongodb都会成为primary,因为它的优先级最高。当primary宕服后,会优先提升vm7-201上的mongodb成为new primary,因为它的优先级是第2高。当宕服的primary恢复后,会抢占primary。

规划的架构(部署的时候)

1

primary宕服后选举new primary

在这里插入图片描述

primary宕服恢复后

在这里插入图片描述

1.3 操作系统环境

### 操作系统版本
[root@vm7-200 ~]# cat /etc/redhat-release;uname -r;uname -m
CentOS Linux release 7.9.2009 (Core)
3.10.0-1160.el7.x86_64
x86_64

### 网卡及配置
[root@vm7-200 ~]# ip addr show ens33
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:8d:d6:eb brd ff:ff:ff:ff:ff:ff
    inet 10.4.7.200/24 brd 10.4.7.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe8d:d6eb/64 scope link 
       valid_lft forever preferred_lft forever

### 能否访问互联网
[root@vm7-200 ~]# ping -l 10.4.7.200 -c 2 www.baidu.com
PING www.a.shifen.com (14.215.177.38) 56(84) bytes of data.
64 bytes from 14.215.177.38 (14.215.177.38): icmp_seq=1 ttl=128 time=34.2 ms
64 bytes from 14.215.177.38 (14.215.177.38): icmp_seq=2 ttl=128 time=34.4 ms

--- www.a.shifen.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 34.239/34.359/34.480/0.221 ms, pipe 2

1.4 操作系统优化

每台服务器的优化如下所示,另我我在优化的时候是没有禁用root用户的,也没有更改ssh服务端口,

#### 创建chenliang用户,同时属于chenliang和wheel组,并同时设置密码
useradd chenliang -G wheel
id chenliang
echo "chenliang"|passwd --stdin chenliang

#### 对chenliang用户进行visudo授权
echo "chenliang ALL=(ALL) NOPASSWD:ALL" >>/etc/sudoers
visudo -c

#### 让用户密码永不过期
cat >>/etc/login.defs<<'EOF'
PASS_MAX_DAYS   99999
PASS_MIN_DAYS   0 
PASS_MIN_LEN    5
PASS_WARN_AGE   7
EOF


#### 关闭 firewalld 服务,不用它来管理 iptables 防火墙
systemctl stop firewalld.service
systemctl disable firewalld.service
systemctl mask firewalld.service 
mv /usr/lib/systemd/system/firewalld.service /usr/lib/systemd/system/firewalld.service.bak


### 安装 ipables-services 防火墙,用它来管理 iptables 防火墙
curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
chattr -i /etc/passwd /etc/shadow /etc/group /etc/gshadow
yum install iptables-services -y

systemctl start iptables
systemctl enable iptables

iptables -t filter -D INPUT -j REJECT --reject-with icmp-host-prohibited     # 删除filter表中INPUT链的第5条规则
iptables -t filter -D FORWARD -j REJECT --reject-with icmp-host-prohibited   # 删除filter表中FORWARD链里唯一的一条规则

iptables-save >/etc/sysconfig/iptables                                       # 保存配置
systemctl restart iptables                                                   # 重启防火墙


#### IPTABLES中添加ssh服务端口(921),后期我再优化ssh服务,不是在这个脚本中
iptables -t filter -A INPUT --dport 921 -j ACCEPT
iptables -t filter -A INPUT -p tcp --dport 921 -j ACCEPT
iptables-save >/etc/sysconfig/iptables



#### 更改base源和epel源
curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
yum install -y epel-release


### 安装常用工具
yum install -y  \
 tree telnet lrzsz wget ntpdate vim  nc namp dos2unix  tcpdump  expect elinks  \
 lsof net-tools iproute  bridge-utils \
 bind-utils nscd \
 gcc gcc-c++ make cmake libaio zlib-devel pcre-devel  \
 psmisclsof sysstat yum-utils 


### 更改主机名(根据你的场景,就是指vm这个前缀,还有根据哪个网卡)
hostnamectl set-hostname  \
   vm$(ip addr show ens33|awk -F "[ /]" 'NR==3{print $6}'|awk -F "." '{print $3"-"$4}').host.com


### 关闭SELINUX
sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config
setenforce 0


### 设置支持中文字符
echo "LANG=\"zh_CN.UTF-8\"" >/etc/locale.conf


### 内核优化
cat >>/etc/sysctl.conf<<'EOF'
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
vm.max_map_count=262144
vm.swappiness=10
EOF
sysctl -p


### 资源描述符
cat >>/etc/security/limits.conf<<EOF
* soft nproc  65535
* hard nproc  65535
* soft nofile 65535
* hard nofile 65535
* soft stack  65535
* hard stack  65535
EOF


echo " * - nproc 65535" >/etc/security/limits.d/20-nproc.conf
echo "session    required    pam_limits.so" >>/etc/pam.d/login



### 校准和更新操作系统的时间
cat >>/etc/sysconfig/clock <<EOF
ZONE="Asia/Shanghai"
UTC=false
ARC=false
EOF

ln -sf /usr/share/zoneinfo/Asia/Shanghai    /etc/localtime

ntpdate ntp1.aliyun.com

/sbin/hwclock --systohc 
hwclock --show


#### 定时更新系统时间
mkdir -p /server/scripts/ 
ls -ld /server/scripts/

cat >/server/scripts/update_os_time.sh << 'EOF'
#!/bin/bash
#
# Define variables
RETVAL=0
Ntp_server=(
ntp.aliyun.com
ntp1.aliyun.com
ntp2.aliyun.com
ntp3.aliyun.com
ntp4.aliyun.com
ntp5.aliyun.com
ntp6.aliyun.com
ntp7.aliyun.com
)
 
# Determine the user to execute
if [ $UID -ne $RETVAL ];then
   echo "Must be root to run scripts"
   exit 1
fi

# Load locall functions library
[ -f /etc/init.d/functions ] && source /etc/init.d/functions

# Install ntpdate command
yum install ntpdate -y >/dev/null 2>&1
 
# for loop update os time
for((i=0;i<${#Ntp_server[*]};i++))
do
    /usr/sbin/ntpdate ${Ntp_server[i]} >/dev/null 2>&1 &
    RETVAL=$?
    if [ $RETVAL -eq 0 ];then
       action "Update os time" /bin/true
       break
      else
       action "Update os time" /bin/false
       continue
    fi
done
 
# Scripts return values
exit $RTVAL
EOF


### 添加定时任务
cat >>/var/spool/cron/root<<'EOF'
# Crond update os time 
*/01 * * * * /bin/sh /server/scripts/update_os_time.sh  >/dev/null 2>&1
EOF

crontab -l|tail -2

第2章 服务器上部署MongoDB软件及服务

2.1 事先生成密钥(不是证书哈)

我这里是生成密钥后,将其下载到我的PC电脑上,后面在部署每个mongodb实例时将其上传到相关的目录,再启动mongodb实例。

openssl rand -base64 756 >qepyd.key
ll qepyd.key

2.2 软件及实例部署前的规划说明

软件部署的位置

/data/mongodb/apps/mongodb
	# 它是个软件链接,指向的是/data/mongodb/apps/mongodb-linux-x86_64-rhel70-4.0.2
	# 后面的实例我用softusermongo用户来启动,所以在安装软件阶段要先创建,后面让其属主/组为softusermongo

实例部署的规划

/data/mongodb/
└── 27017                    # 以端口区分每个实例
    ├── conf                 # 存放27017实例的配置文件
    ├── data                 # 存放27017实例的数据文件
    ├── keys                 # 存放副本集通信的密钥文件,副本集中每个节点的文件及内容都相同;
    ├── logs                 # 存放27017实例的日志文件
    ├── run                  # 存放27017实例的pid和socket文件
    └── scripts              # 存放27017实例的相关脚本(启停脚本、数据备份脚本等)

2.3 所有服务器部署MongoDB软件

事先下载好软件

因为我的操作系统是CentOS 7.9,所以我这里只给出相应平台下相应软件版本的下载地址

https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.0.2.tgz

所有服务器上部署软件的步骤

注意:在所有服务器上进行MongoDB软件,都按以下的进行操作。

#### 创建软件的安装目录
sudo  mkdir -p /data/mongodb/apps
sudo  ls -ld /data/mongodb/apps

#### 创建mongodb用户
sudo  chattr -i /etc/passwd /etc/shadow /etc/group /etc/gshadow
sudo  useradd softusermongo  -s /sbin/nologin  # 创建用户softusermongo用户,不让其登录,但是有家目录,但是有家目录的,到于名称,纯属个人习惯
sudo  id softusermongo

#### 上传软件包进行安装
ll mongodb-linux-x86_64-rhel70-4.0.2.tgz
sudo  tar xf mongodb-linux-x86_64-rhel70-4.0.2.tgz -C /data/mongodb/apps/
sudo  ln -sv /data/mongodb/apps/mongodb-linux-x86_64-rhel70-4.0.2 /data/mongodb/apps/mongodb
sudo  ls -l /data/mongodb/apps/mongodb
sudo  chown -R softusermongo:softusermongo /data/mongodb/

#### 配置环境变量
sudo  ls -ld /data/mongodb/apps/mongodb/bin
sudo  su - root -c "echo "PATH=/data/mongodb/apps/mongodb/bin:\$PATH" >>/etc/profile"
source  /etc/profile
echo  $PATH
which mongo mongod

#### 查看其版本
mongod --version|head -1

2.4 vm-7-201上部署mongodb实例

#### 创建相关的目录
sudo  mkdir -p /data/mongodb/27017/{data,conf,keys,logs,run,scripts}
sudo  tree /data/mongodb/27017

#### 准备27017实例的配置文件(简化版)
sudo su - root -c   "cat >>/data/mongodb/27017/conf/mongodb.conf<<'EOF'
net:
  port: 27017
  bindIpAll: false
  bindIp: "10.4.7.201,127.0.0.1"       # 注意我监听的IP地址,127.0.0.1有用的哈
processManagement:
  fork: true
  pidFilePath: "/data/mongodb/27017/run/mongod.pid"
storage:
  dbPath: /data/mongodb/27017/data
  journal:
    enabled: true
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/27017/logs/mongodb.log
replication:
  replSetName: "qepyd"                 # 副本集的名称,各节点要统一样
security:
  keyFile: "/data/mongodb/27017/keys/qepyd.key"
  authorization: "enabled"
EOF
"

#### 上传密钥文件
cd /data/mongodb/27017/keys/
sudo rz 
ll qepyd.key
sudo chmod 700 qepyd.key

#### 更改/data/mongodb/目录极其子目录的属主/组
sudo  chown -R softusermongo:softusermongo  /data/mongodb/

#### 准备启停脚本
01:将 https://chenliang.blog.csdn.net/article/details/105238273  博客 1.3 章节的脚本内容进行复制
02:vim mongod后把其内容放在里面,保存退出;
03:然后执行以下的操作
sudo mv mongod /data/mongodb/27017/scripts/
sudo chmod 700 /data/mongodb/27017/scripts/mongod
sudo chown -R softusermongo:softusermongo /data/mongodb/

#### 启动mongodb实例
sudo su - softusermongo -s /bin/bash -c "/data/mongodb/27017/scripts/mongod start"
sudo lsof -i :27017

#### 加入开机自启动
sudo su - root -c "cat >>/etc/rc.local<<EOF

# Boot start mongodb service. USER:chenliang TIME:$(date +%F)
su - softusermongo -s /bin/bash -c \"/data/mongodb/27017/scripts/mongod start\"

EOF
"

#### 给/etc/rc.d/rc.local加执行权限
sudo chmod 744 /etc/rc.d/rc.local
sudo tail -3 /etc/rc.d/rc.local

2.5 vm-7-202上部署mongodb实例

#### 创建相关的目录
sudo  mkdir -p /data/mongodb/27017/{data,conf,keys,logs,run,scripts}
sudo  tree /data/mongodb/27017

#### 准备27017实例的配置文件(简化版)
sudo su - root -c   "cat >>/data/mongodb/27017/conf/mongodb.conf<<'EOF'
net:
  port: 27017
  bindIpAll: false
  bindIp: "10.4.7.202,127.0.0.1"        # 注意我监听的IP地址,127.0.0.1有用的哈
processManagement:
  fork: true
  pidFilePath: "/data/mongodb/27017/run/mongod.pid"
storage:
  dbPath: /data/mongodb/27017/data
  journal:
    enabled: true
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/27017/logs/mongodb.log
replication:
  replSetName: "qepyd"                 # 副本集的名称,各节点要统一
security:
  keyFile: "/data/mongodb/27017/keys/qepyd.key"
  authorization: "enabled"
EOF
"

#### 上传密钥文件
cd /data/mongodb/27017/keys/
sudo rz 
ll qepyd.key
sudo chmod 700 qepyd.key


#### 更改/data/mongodb/目录极其子目录的属主/组
sudo  chown -R softusermongo:softusermongo  /data/mongodb/


#### 准备启停脚本
01:将 https://chenliang.blog.csdn.net/article/details/105238273  博客 1.3 章节的脚本内容进行复制
02:vim mongod后把其内容放在里面,保存退出;
03:然后执行以下的操作
sudo mv mongod /data/mongodb/27017/scripts/
sudo chmod 700 /data/mongodb/27017/scripts/mongod
sudo chown -R softusermongo:softusermongo /data/mongodb/

#### 启动mongodb实例
sudo su - softusermongo -s /bin/bash -c "/data/mongodb/27017/scripts/mongod start"
sudo lsof -i :27017

#### 加入开机自启动
sudo su - root -c "cat >>/etc/rc.local<<EOF

# Boot start mongodb service. USER:chenliang TIME:$(date +%F)
su - softusermongo -s /bin/bash -c \"/data/mongodb/27017/scripts/mongod start\"

EOF
"

#### 给/etc/rc.d/rc.local加执行权限
sudo chmod 744 /etc/rc.d/rc.local
sudo tail -3 /etc/rc.d/rc.local

2.6 vm-7-203上部署mongodb实例

#### 创建相关的目录
sudo  mkdir -p /data/mongodb/27017/{data,conf,keys,logs,run,scripts}
sudo  tree /data/mongodb/27017

#### 准备27017实例的配置文件(简化版)
sudo su - root -c   "cat >>/data/mongodb/27017/conf/mongodb.conf<<'EOF'
net:
  port: 27017
  bindIpAll: false
  bindIp: "10.4.7.203,127.0.0.1"      # 注意我监听的IP地址,127.0.0.1有用的哈
processManagement:
  fork: true
  pidFilePath: "/data/mongodb/27017/run/mongod.pid"
storage:
  dbPath: /data/mongodb/27017/data
  journal:
    enabled: true
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/27017/logs/mongodb.log
replication:
  replSetName: "qepyd"                 # 副本集的名称,各节点要统一
security:
  keyFile: "/data/mongodb/27017/keys/qepyd.key"
  authorization: "enabled"
EOF
"

#### 上传密钥文件
cd /data/mongodb/27017/keys/
sudo rz 
ll qepyd.key
sudo chmod 700 qepyd.key


#### 更改/data/mongodb/目录极其子目录的属主/组
sudo  chown -R softusermongo:softusermongo  /data/mongodb/


#### 准备启停脚本
01:将 https://chenliang.blog.csdn.net/article/details/105238273  博客 1.3 章节的脚本内容进行复制
02:vim mongod后把其内容放在里面,保存退出;
03:然后执行以下的操作
sudo mv mongod /data/mongodb/27017/scripts/
sudo chmod 700 /data/mongodb/27017/scripts/mongod
sudo chown -R softusermongo:softusermongo /data/mongodb/

#### 启动mongodb实例
sudo su - softusermongo -s /bin/bash -c "/data/mongodb/27017/scripts/mongod start"
sudo lsof -i :27017


#### 加入开机自启动
sudo su - root -c "cat >>/etc/rc.local<<EOF

# Boot start mongodb service. USER:chenliang TIME:$(date +%F)
su - softusermongo -s /bin/bash -c \"/data/mongodb/27017/scripts/mongod start\"

EOF
"


#### 给/etc/rc.d/rc.local加执行权限
sudo chmod 744 /etc/rc.d/rc.local
sudo tail -3 /etc/rc.d/rc.local

第3章 MongoDB副本集的初始化以及验证

3.1 副本集的初始化

注意:我当前是在vm7-201节点上的mongodb上执行的,我让它在初始化时成为primary,因为我后面指定各节点的优先级都为1,这里让其成为primary只是我规划的,当它成了primary后又宕服恢复后,它不会进行主的抢占。

// 连接至mongodb实例,注意我用的是127.0.0.1
mongo  127.0.0.1:27017


//  切换到admin库下,定义一个变量config
use admin;
config = {
    "_id":"qepyd",    // 这是我副本集的名称
    "members":[
                {"_id":0,host:"10.4.7.201:27017",priority:10},
                {"_id":1,host:"10.4.7.202:27017",priority:9},   
                {"_id":2,host:"10.4.7.203:27017",priority:8} 
    ]
}

rs.initiate( config );


// 查看副本集的状态,你可以看到个节点是primary,哪些节点是secondary
rs.status()


// 等待一会,当前节点(vm7-201)就会成为primary
rs.status()

3.2 创建两管理帐号

**给MongoDB实例创建超级由帐号,我这是在primary上操作的,会同步至secondary **

[chenliang@vm7-201 ~]$ mongo 127.0.0.1:27017
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:27017/test
MongoDB server version: 4.0.2
qepyd:PRIMARY> 
qepyd:PRIMARY> 
qepyd:PRIMARY> use admin;                   // 进入admin库
switched to db admin
qepyd:PRIMARY> 
qepyd:PRIMARY> 
qepyd:PRIMARY> db.createUser(
...     {
...         "user":"root",
...         "pwd":"root123456",
...         "roles":["root"]
...     }
... )
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
qepyd:PRIMARY> 
qepyd:PRIMARY> 
qepyd:PRIMARY> db.auth("root","root123456")     // 进行认证
1
qepyd:PRIMARY>
qepyd:PRIMARY> exit                            // 退出
bye

给我这个管理员创建一个超级帐号,我这是在primary上操作的,会同步至secondary

[chenliang@vm7-201 ~]$ mongo 10.4.7.201:27017 --username=root --password=root123456 --authenticationDatabase=admin
qepyd:PRIMARY> 
qepyd:PRIMARY> 
qepyd:PRIMARY> use admin;
switched to db admin
qepyd:PRIMARY> 
qepyd:PRIMARY> 
 qepyd:PRIMARY> db.createUser(
...     {
...         "user":"chenliang",
...         "pwd":"chenliang123456",
...         "roles":["root"]
...     }
... )
Successfully added user: { "user" : "chenliang", "roles" : [ "root" ] }
qepyd:PRIMARY> 
qepyd:PRIMARY> 
qepyd:PRIMARY> exit
bye

3.3 各节点集合状态

在primary(vm7-201)上面查看

[chenliang@vm7-201 ~]$  mongo 10.4.7.201:27017 --username=root --password=root123456 --authenticationDatabase=admin
MongoDB shell version v4.0.2
connecting to: mongodb://10.4.7.201:27017/test
MongoDB server version: 4.0.2
qepyd:PRIMARY> 
qepyd:PRIMARY> 
qepyd:PRIMARY> rs.status()              // 副本集的查看状态
{
	"set" : "qepyd",
	"date" : ISODate("2021-04-06T09:17:18.979Z"),
	"myState" : 1,
	"term" : NumberLong(1),
	"syncingTo" : "",
	"syncSourceHost" : "",
	"syncSourceId" : -1,
	"heartbeatIntervalMillis" : NumberLong(2000),
	"optimes" : {
		"lastCommittedOpTime" : {
			"ts" : Timestamp(1617700635, 1),
			"t" : NumberLong(1)
		},
		"readConcernMajorityOpTime" : {
			"ts" : Timestamp(1617700635, 1),
			"t" : NumberLong(1)
		},
		"appliedOpTime" : {
			"ts" : Timestamp(1617700635, 1),
			"t" : NumberLong(1)
		},
		"durableOpTime" : {
			"ts" : Timestamp(1617700635, 1),
			"t" : NumberLong(1)
		}
	},
	"lastStableCheckpointTimestamp" : Timestamp(1617700616, 1),
	"members" : [
		{
			"_id" : 0,
			"name" : "10.4.7.201:27017",
			"health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY",
			"uptime" : 67816,
			"optime" : {
				"ts" : Timestamp(1617700635, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-04-06T09:17:15Z"),
			"syncingTo" : "",
			"syncSourceHost" : "",
			"syncSourceId" : -1,
			"infoMessage" : "could not find member to sync from",
			"electionTime" : Timestamp(1617700563, 1),
			"electionDate" : ISODate("2021-04-06T09:16:03Z"),
			"configVersion" : 1,
			"self" : true,
			"lastHeartbeatMessage" : ""
		},
		{
			"_id" : 1,
			"name" : "10.4.7.202:27017",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 86,
			"optime" : {
				"ts" : Timestamp(1617700635, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1617700635, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-04-06T09:17:15Z"),
			"optimeDurableDate" : ISODate("2021-04-06T09:17:15Z"),
			"lastHeartbeat" : ISODate("2021-04-06T09:17:18.091Z"),
			"lastHeartbeatRecv" : ISODate("2021-04-06T09:17:17.970Z"),
			"pingMs" : NumberLong(0),
			"lastHeartbeatMessage" : "",
			"syncingTo" : "10.4.7.201:27017",
			"syncSourceHost" : "10.4.7.201:27017",
			"syncSourceId" : 0,
			"infoMessage" : "",
			"configVersion" : 1
		},
		{
			"_id" : 2,
			"name" : "10.4.7.203:27017",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 86,
			"optime" : {
				"ts" : Timestamp(1617700635, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1617700635, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-04-06T09:17:15Z"),
			"optimeDurableDate" : ISODate("2021-04-06T09:17:15Z"),
			"lastHeartbeat" : ISODate("2021-04-06T09:17:18.091Z"),
			"lastHeartbeatRecv" : ISODate("2021-04-06T09:17:17.964Z"),
			"pingMs" : NumberLong(1),
			"lastHeartbeatMessage" : "",
			"syncingTo" : "10.4.7.201:27017",
			"syncSourceHost" : "10.4.7.201:27017",
			"syncSourceId" : 0,
			"infoMessage" : "",
			"configVersion" : 1
		}
	],
	"ok" : 1,
	"operationTime" : Timestamp(1617700635, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1617700635, 1),
		"signature" : {
			"hash" : BinData(0,"9drseCBuiZhX1sjA4A3u7Klzpjg="),
			"keyId" : NumberLong("6947971021395722241")
		}
	}
}
qepyd:PRIMARY>
qepyd:PRIMARY>
qepyd:PRIMARY> rs.config()                       // 查看副本集的配置
{
	"_id" : "qepyd",
	"version" : 1,
	"protocolVersion" : NumberLong(1),
	"writeConcernMajorityJournalDefault" : true,
	"members" : [
		{
			"_id" : 0,
			"host" : "10.4.7.201:27017",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 10,
			"tags" : {
				
			},
			"slaveDelay" : NumberLong(0),
			"votes" : 1
		},
		{
			"_id" : 1,
			"host" : "10.4.7.202:27017",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 9,
			"tags" : {
				
			},
			"slaveDelay" : NumberLong(0),
			"votes" : 1
		},
		{
			"_id" : 2,
			"host" : "10.4.7.203:27017",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 8,
			"tags" : {
				
			},
			"slaveDelay" : NumberLong(0),
			"votes" : 1
		}
	],
	"settings" : {
		"chainingAllowed" : true,
		"heartbeatIntervalMillis" : 2000,
		"heartbeatTimeoutSecs" : 10,
		"electionTimeoutMillis" : 10000,
		"catchUpTimeoutMillis" : -1,
		"catchUpTakeoverDelayMillis" : 30000,
		"getLastErrorModes" : {
			
		},
		"getLastErrorDefaults" : {
			"w" : 1,
			"wtimeout" : 0
		},
		"replicaSetId" : ObjectId("606c26c84a87108e5e29b098")
	}
}

在SECONDARY(vm7-202)上面查看

[chenliang@vm7-202 ~]$ mongo 10.4.7.202:27017 --username=root --password=root123456 --authenticationDatabase=admin
qepyd:SECONDARY> 
qepyd:SECONDARY>
qepyd:SECONDARY> 
qepyd:SECONDARY>
qepyd:SECONDARY> rs.status()               // 查看副本集的状态
{
	"set" : "qepyd",
	"date" : ISODate("2021-04-06T09:18:07.688Z"),
	"myState" : 2,
	"term" : NumberLong(1),
	"syncingTo" : "10.4.7.201:27017",
	"syncSourceHost" : "10.4.7.201:27017",
	"syncSourceId" : 0,
	"heartbeatIntervalMillis" : NumberLong(2000),
	"optimes" : {
		"lastCommittedOpTime" : {
			"ts" : Timestamp(1617700685, 1),
			"t" : NumberLong(1)
		},
		"readConcernMajorityOpTime" : {
			"ts" : Timestamp(1617700685, 1),
			"t" : NumberLong(1)
		},
		"appliedOpTime" : {
			"ts" : Timestamp(1617700685, 1),
			"t" : NumberLong(1)
		},
		"durableOpTime" : {
			"ts" : Timestamp(1617700685, 1),
			"t" : NumberLong(1)
		}
	},
	"lastStableCheckpointTimestamp" : Timestamp(1617700616, 1),
	"members" : [
		{
			"_id" : 0,
			"name" : "10.4.7.201:27017",
			"health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY",
			"uptime" : 129,
			"optime" : {
				"ts" : Timestamp(1617700685, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1617700685, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-04-06T09:18:05Z"),
			"optimeDurableDate" : ISODate("2021-04-06T09:18:05Z"),
			"lastHeartbeat" : ISODate("2021-04-06T09:18:06.229Z"),
			"lastHeartbeatRecv" : ISODate("2021-04-06T09:18:05.848Z"),
			"pingMs" : NumberLong(0),
			"lastHeartbeatMessage" : "",
			"syncingTo" : "",
			"syncSourceHost" : "",
			"syncSourceId" : -1,
			"infoMessage" : "",
			"electionTime" : Timestamp(1617700563, 1),
			"electionDate" : ISODate("2021-04-06T09:16:03Z"),
			"configVersion" : 1
		},
		{
			"_id" : 1,
			"name" : "10.4.7.202:27017",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 67864,
			"optime" : {
				"ts" : Timestamp(1617700685, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-04-06T09:18:05Z"),
			"syncingTo" : "10.4.7.201:27017",
			"syncSourceHost" : "10.4.7.201:27017",
			"syncSourceId" : 0,
			"infoMessage" : "",
			"configVersion" : 1,
			"self" : true,
			"lastHeartbeatMessage" : ""
		},
		{
			"_id" : 2,
			"name" : "10.4.7.203:27017",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 129,
			"optime" : {
				"ts" : Timestamp(1617700685, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1617700685, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-04-06T09:18:05Z"),
			"optimeDurableDate" : ISODate("2021-04-06T09:18:05Z"),
			"lastHeartbeat" : ISODate("2021-04-06T09:18:06.231Z"),
			"lastHeartbeatRecv" : ISODate("2021-04-06T09:18:06.228Z"),
			"pingMs" : NumberLong(1),
			"lastHeartbeatMessage" : "",
			"syncingTo" : "10.4.7.201:27017",
			"syncSourceHost" : "10.4.7.201:27017",
			"syncSourceId" : 0,
			"infoMessage" : "",
			"configVersion" : 1
		}
	],
	"ok" : 1,
	"operationTime" : Timestamp(1617700685, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1617700685, 1),
		"signature" : {
			"hash" : BinData(0,"i2cH3xThiit8pCQsIxnV4n0WFmc="),
			"keyId" : NumberLong("6947971021395722241")
		}
	}
}
qepyd:SECONDARY>
qepyd:SECONDARY>
qepyd:SECONDARY>
qepyd:SECONDARY>
qepyd:SECONDARY> rs.config()                  // 查看副本集的配置
{
	"_id" : "qepyd",
	"version" : 1,
	"protocolVersion" : NumberLong(1),
	"writeConcernMajorityJournalDefault" : true,
	"members" : [
		{
			"_id" : 0,
			"host" : "10.4.7.201:27017",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 10,
			"tags" : {
				
			},
			"slaveDelay" : NumberLong(0),
			"votes" : 1
		},
		{
			"_id" : 1,
			"host" : "10.4.7.202:27017",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 9,
			"tags" : {
				
			},
			"slaveDelay" : NumberLong(0),
			"votes" : 1
		},
		{
			"_id" : 2,
			"host" : "10.4.7.203:27017",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 8,
			"tags" : {
				
			},
			"slaveDelay" : NumberLong(0),
			"votes" : 1
		}
	],
	"settings" : {
		"chainingAllowed" : true,
		"heartbeatIntervalMillis" : 2000,
		"heartbeatTimeoutSecs" : 10,
		"electionTimeoutMillis" : 10000,
		"catchUpTimeoutMillis" : -1,
		"catchUpTakeoverDelayMillis" : 30000,
		"getLastErrorModes" : {
			
		},
		"getLastErrorDefaults" : {
			"w" : 1,
			"wtimeout" : 0
		},
		"replicaSetId" : ObjectId("606c26c84a87108e5e29b098")
	}
}

在SECONDARY(vm7-203)上面查看

[chenliang@vm7-203 ~]$ mongo 10.4.7.203:27017 --username=root --password=root123456 --authenticationDatabase=admin
qepyd:SECONDARY> 
qepyd:SECONDARY> 
qepyd:SECONDARY> 
qepyd:SECONDARY> rs.status()               // 查看副本集的状态
{
	"set" : "qepyd",
	"date" : ISODate("2021-04-06T09:18:07.688Z"),
	"myState" : 2,
	"term" : NumberLong(1),
	"syncingTo" : "10.4.7.201:27017",
	"syncSourceHost" : "10.4.7.201:27017",
	"syncSourceId" : 0,
	"heartbeatIntervalMillis" : NumberLong(2000),
	"optimes" : {
		"lastCommittedOpTime" : {
			"ts" : Timestamp(1617700685, 1),
			"t" : NumberLong(1)
		},
		"readConcernMajorityOpTime" : {
			"ts" : Timestamp(1617700685, 1),
			"t" : NumberLong(1)
		},
		"appliedOpTime" : {
			"ts" : Timestamp(1617700685, 1),
			"t" : NumberLong(1)
		},
		"durableOpTime" : {
			"ts" : Timestamp(1617700685, 1),
			"t" : NumberLong(1)
		}
	},
	"lastStableCheckpointTimestamp" : Timestamp(1617700616, 1),
	"members" : [
		{
			"_id" : 0,
			"name" : "10.4.7.201:27017",
			"health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY",
			"uptime" : 129,
			"optime" : {
				"ts" : Timestamp(1617700685, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1617700685, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-04-06T09:18:05Z"),
			"optimeDurableDate" : ISODate("2021-04-06T09:18:05Z"),
			"lastHeartbeat" : ISODate("2021-04-06T09:18:06.229Z"),
			"lastHeartbeatRecv" : ISODate("2021-04-06T09:18:05.848Z"),
			"pingMs" : NumberLong(0),
			"lastHeartbeatMessage" : "",
			"syncingTo" : "",
			"syncSourceHost" : "",
			"syncSourceId" : -1,
			"infoMessage" : "",
			"electionTime" : Timestamp(1617700563, 1),
			"electionDate" : ISODate("2021-04-06T09:16:03Z"),
			"configVersion" : 1
		},
		{
			"_id" : 1,
			"name" : "10.4.7.202:27017",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 67864,
			"optime" : {
				"ts" : Timestamp(1617700685, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-04-06T09:18:05Z"),
			"syncingTo" : "10.4.7.201:27017",
			"syncSourceHost" : "10.4.7.201:27017",
			"syncSourceId" : 0,
			"infoMessage" : "",
			"configVersion" : 1,
			"self" : true,
			"lastHeartbeatMessage" : ""
		},
		{
			"_id" : 2,
			"name" : "10.4.7.203:27017",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 129,
			"optime" : {
				"ts" : Timestamp(1617700685, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1617700685, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-04-06T09:18:05Z"),
			"optimeDurableDate" : ISODate("2021-04-06T09:18:05Z"),
			"lastHeartbeat" : ISODate("2021-04-06T09:18:06.231Z"),
			"lastHeartbeatRecv" : ISODate("2021-04-06T09:18:06.228Z"),
			"pingMs" : NumberLong(1),
			"lastHeartbeatMessage" : "",
			"syncingTo" : "10.4.7.201:27017",
			"syncSourceHost" : "10.4.7.201:27017",
			"syncSourceId" : 0,
			"infoMessage" : "",
			"configVersion" : 1
		}
	],
	"ok" : 1,
	"operationTime" : Timestamp(1617700685, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1617700685, 1),
		"signature" : {
			"hash" : BinData(0,"i2cH3xThiit8pCQsIxnV4n0WFmc="),
			"keyId" : NumberLong("6947971021395722241")
		}
	}
}
qepyd:SECONDARY>
qepyd:SECONDARY>
qepyd:SECONDARY>
qepyd:SECONDARY>
qepyd:SECONDARY> rs.config()                  // 查看副本集的配置
{
	"_id" : "qepyd",
	"version" : 1,
	"protocolVersion" : NumberLong(1),
	"writeConcernMajorityJournalDefault" : true,
	"members" : [
		{
			"_id" : 0,
			"host" : "10.4.7.201:27017",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 10,
			"tags" : {
				
			},
			"slaveDelay" : NumberLong(0),
			"votes" : 1
		},
		{
			"_id" : 1,
			"host" : "10.4.7.202:27017",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 9,
			"tags" : {
				
			},
			"slaveDelay" : NumberLong(0),
			"votes" : 1
		},
		{
			"_id" : 2,
			"host" : "10.4.7.203:27017",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 8,
			"tags" : {
				
			},
			"slaveDelay" : NumberLong(0),
			"votes" : 1
		}
	],
	"settings" : {
		"chainingAllowed" : true,
		"heartbeatIntervalMillis" : 2000,
		"heartbeatTimeoutSecs" : 10,
		"electionTimeoutMillis" : 10000,
		"catchUpTimeoutMillis" : -1,
		"catchUpTakeoverDelayMillis" : 30000,
		"getLastErrorModes" : {
			
		},
		"getLastErrorDefaults" : {
			"w" : 1,
			"wtimeout" : 0
		},
		"replicaSetId" : ObjectId("606c26c84a87108e5e29b098")
	}
}

3.4 Navicat客户端工具连接副本集

Navicat连接副本集

1

在这里插入图片描述

3.5 Navicat客户端上产生测试数据

我这里是在Navicat上执行的

use chenliang;
db.lili.insert({"name":"lili01","age":21});
db.lili.insert({"name":"lili02","age":22});
db.lili.insert({"name":"lili03","age":23});
db.lili.insert({"name":"lili04","age":24});
db.lili.find()

在这里插入图片描述

在secondary(vm7-202)上查看数据(我这是在操作系统命令行上执行)

[chenliang@vm7-202 ~]$ mongo 10.4.7.202:27017 --username=root --password=root123456 --authenticationDatabase=admin
qepyd:SECONDARY>
qepyd:SECONDARY>
qepyd:SECONDARY> rs.slaveOk()       // 声明一下,表示我要读取数据了
qepyd:SECONDARY>
qepyd:SECONDARY> use chenliang;     // 进入到chenliang库下
switched to db chenliang
qepyd:SECONDARY> 
qepyd:SECONDARY> db.lili.find({})  // 查看lili集合中所有的数据
{ "_id" : ObjectId("606c17b3f40e0000e4000383"), "name" : "lili01", "age" : 21 }
{ "_id" : ObjectId("606c17b3f40e0000e4000385"), "name" : "lili03", "age" : 23 }
{ "_id" : ObjectId("606c17b3f40e0000e4000384"), "name" : "lili02", "age" : 22 }
{ "_id" : ObjectId("606c17b3f40e0000e4000386"), "name" : "lili04", "age" : 24 }

在secondary(vm7-203)上查看数据(我这是在操作系统命令行上执行)

[chenliang@vm7-203 ~]$ mongo 10.4.7.203:27017 --username=root --password=root123456 --authenticationDatabase=admin
qepyd:SECONDARY>
qepyd:SECONDARY>
qepyd:SECONDARY> rs.slaveOk()       // 声明一下,表示我要读取数据了
qepyd:SECONDARY>
qepyd:SECONDARY> use chenliang;     // 进入到chenliang库下
switched to db chenliang
qepyd:SECONDARY> 
qepyd:SECONDARY> db.lili.find({})  // 查看lili集合中所有的数据
{ "_id" : ObjectId("606c17b3f40e0000e4000383"), "name" : "lili01", "age" : 21 }
{ "_id" : ObjectId("606c17b3f40e0000e4000385"), "name" : "lili03", "age" : 23 }
{ "_id" : ObjectId("606c17b3f40e0000e4000384"), "name" : "lili02", "age" : 22 }
{ "_id" : ObjectId("606c17b3f40e0000e4000386"), "name" : "lili04", "age" : 24 }

3.6 Primary上删除之前的测试数据

还是在navicat上进行操作

use chenliang;
db.dropDatabase();

3.7 其实还应该为业务创建相关帐号 ?

标签:副本,10.4,MongoDB,27017,qepyd,NumberLong,mongodb,PSS,SECONDARY
来源: https://blog.csdn.net/weixin_43733154/article/details/115466605