Linux环境下mongodb副本集搭建与基本操作


前言

linux环境下mongoDB的安装部署请参考我之前的文章:linux环境下mongodb的安装

mongoDB 6.0版本之后。mongoDB安装目录的bin目录下是没有mongo.exe文件的,所以想要使用mongo,需要自行从mongodb官网下载

一、下载安装

1.1 下载mongosh

打开mongosh安装手册点击蓝字进入下载界面
在这里插入图片描述

选择适合自己的版本,此处下载Linux x64版本,tgz包进行示例(本系统为Cent OS 7.0)其他下载方法,请参考mongosh安装手册

在这里插入图片描述
将下载好的tgz文件上传到虚拟机(可使用finalshell,也可以vm tools
在这里插入图片描述

1.2 mongosh安装

//解压到指定文件夹
tar -zxvf mongosh-2.0.2-linux-x64.tgz -C /usr/local/mongodb/
//文件重命名
mv /usr/local/mongodb/mongosh-2.0.2-linux-x64 /usr/local/mongodb/mongosh

1.3 配置环境变量

//打开环境变量配置文件
vim /etc/porfile
//添加mongosh的环境变量
export PATH=/usr/local/mongodb/mongosh/bin:$PATH
//退出编辑
:wq
//使配置生效
source /etc/profile

1.4 配置启动文件

所有设备配置相同

vim /etc/mongodb.conf
//文件内容
dbpath=/var/lib/mongodb
logpath=/var/log/mongodb/mongod.log
logappend=true
port=27017
bind_ip=0.0.0.0
fork=true
replSet=repl_0

1.4 安装测试

mongosh 后面的内容替换为你本机的IP地址,和mongodb.conf中配置的端口号

//启动mongodb
mongod -f /etc/mongodb.conf
//进入mongo
mongosh 192.168.88.101:27017

成功后会输出以下:

[root@node1 hadoop]# mongosh 192.168.88.101:27017
Current Mongosh Log ID: 6535d7a29462ea49e88230a4
Connecting to:          mongodb://192.168.88.101:27017/?directConnection=true&appName=mongosh+2.0.2
Using MongoDB:          7.0.2
Using Mongosh:          2.0.2

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting
   2023-10-23T10:16:45.189+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2023-10-23T10:16:45.189+08:00: You are running this process as the root user, which is not recommended
   2023-10-23T10:16:45.191+08:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
   2023-10-23T10:16:45.191+08:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'
   2023-10-23T10:16:45.191+08:00: Soft rlimits for open file descriptors too low
------


Deprecation warnings:
  - Using mongosh on the current operating system is deprecated, and support may be removed in a future release.
See https://www.mongodb.com/docs/mongodb-shell/install/#supported-operating-systems for documentation on supported platforms.
test>

在这里插入图片描述

二、配置副本集

2.1 副本集的初始化

需要所有设备启动mongodb

> use admin
switched to db admin

>tang={_id:"repl_0", members:[ {_id:0,host:'192.168.88.101:27017',priority:2}, {_id:1,host:'192.168.88.102:27017',priority:1}, {_id:2,host:'192.168.88.103:27017',arbiterOnly:true}]};

tang可以是任意的名字,不要和mongodb的关键字重复即可。
最外层的_id表示replica set的名字,members里包含的是所有节点的地址以及优先级。优先级最高的即成为主节点,即这里的’192.168.88.101:27017’。特别注意的是,对于仲裁节点,需要有个特别的配置——arbiterOnly:true。这个不能少了,不然主备模式就不能生效。

输出:

{
  _id: 'repl_0',
  members: [
    { _id: 0, host: '192.168.88.101:27017', priority: 2 },
    { _id: 1, host: '192.168.88.102:27017', priority: 1 },
    { _id: 2, host: '192.168.88.103:27017', arbiterOnly: true }
  ]
}

使得配置生效

> rs.initiate(tang)

输出:

{ ok: 1 }
repl_0 [direct: other] 

2.2 查看副本集成员状态信息

代码如下(示例):

 rs.status()

配置成功实例:

{
  set: 'repl_0',
  date: ISODate("2023-10-23T02:28:17.871Z"),
  myState: 1,
  term: Long("1"),
  syncSourceHost: '',
  syncSourceId: -1,
  heartbeatIntervalMillis: Long("2000"),
  majorityVoteCount: 2,
  writeMajorityCount: 2,
  votingMembersCount: 3,
  writableVotingMembersCount: 2,
  optimes: {
    lastCommittedOpTime: { ts: Timestamp({ t: 1698028095, i: 1 }), t: Long("1") },
    lastCommittedWallTime: ISODate("2023-10-23T02:28:15.228Z"),
    readConcernMajorityOpTime: { ts: Timestamp({ t: 1698028095, i: 1 }), t: Long("1") },
    appliedOpTime: { ts: Timestamp({ t: 1698028095, i: 1 }), t: Long("1") },
    durableOpTime: { ts: Timestamp({ t: 1698028095, i: 1 }), t: Long("1") },
    lastAppliedWallTime: ISODate("2023-10-23T02:28:15.228Z"),
    lastDurableWallTime: ISODate("2023-10-23T02:28:15.228Z")
  },
  lastStableRecoveryTimestamp: Timestamp({ t: 1698028065, i: 1 }),
  electionCandidateMetrics: {
    lastElectionReason: 'electionTimeout',
    lastElectionDate: ISODate("2023-10-23T02:26:05.171Z"),
    electionTerm: Long("1"),
    lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1698027954, i: 1 }), t: Long("-1") },
    lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1698027954, i: 1 }), t: Long("-1") },
    numVotesNeeded: 2,
    priorityAtElection: 2,
    electionTimeoutMillis: Long("10000"),
    numCatchUpOps: Long("0"),
    newTermStartDate: ISODate("2023-10-23T02:26:05.209Z"),
    wMajorityWriteAvailabilityDate: ISODate("2023-10-23T02:26:05.703Z")
  },
  members: [
    {
      _id: 0,
      name: '192.168.88.101:27017',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 693,
      optime: { ts: Timestamp({ t: 1698028095, i: 1 }), t: Long("1") },
      optimeDate: ISODate("2023-10-23T02:28:15.000Z"),
      lastAppliedWallTime: ISODate("2023-10-23T02:28:15.228Z"),
      lastDurableWallTime: ISODate("2023-10-23T02:28:15.228Z"),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1698027965, i: 1 }),
      electionDate: ISODate("2023-10-23T02:26:05.000Z"),
      configVersion: 1,
      configTerm: 1,
      self: true,
      lastHeartbeatMessage: ''
    },
    {
      _id: 1,
      name: '192.168.88.102:27017',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 143,
      optime: { ts: Timestamp({ t: 1698028095, i: 1 }), t: Long("1") },
      optimeDurable: { ts: Timestamp({ t: 1698028095, i: 1 }), t: Long("1") },
      optimeDate: ISODate("2023-10-23T02:28:15.000Z"),
      optimeDurableDate: ISODate("2023-10-23T02:28:15.000Z"),
      lastAppliedWallTime: ISODate("2023-10-23T02:28:15.228Z"),
      lastDurableWallTime: ISODate("2023-10-23T02:28:15.228Z"),
      lastHeartbeat: ISODate("2023-10-23T02:28:17.282Z"),
      lastHeartbeatRecv: ISODate("2023-10-23T02:28:16.280Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.88.101:27017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 1
    },
    {
      _id: 2,
      name: '192.168.88.103:27017',
      health: 1,
      state: 7,
      stateStr: 'ARBITER',
      uptime: 143,
      lastHeartbeat: ISODate("2023-10-23T02:28:17.282Z"),
      lastHeartbeatRecv: ISODate("2023-10-23T02:28:17.282Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: '',
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      configVersion: 1,
      configTerm: 1
    }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1698028095, i: 1 }),
    signature: {
      hash: Binary.createFromBase64("AAAAAAAAAAAAAAAAAAAAAAAAAAA=", 0),
      keyId: Long("0")
    }
  },
  operationTime: Timestamp({ t: 1698028095, i: 1 })
}

正在配置会显示:

"stateStr" : "RECOVERING"  

至此,副本集配置完成

三、副本集基本操作

3.1 创建数据库

> use test
already on db test

3.2 创建集合/插入数据

创建一个名为 user 的集合,并插入一条文档。这里我们以插入一个用户的信息为例

>db.user.insertOne({name: "Alice", age: 25, gender: "female"})

{
  acknowledged: true,
  insertedId: ObjectId("6536037cc9af5da41534a5bb")
}

3.3 同步副本文档

连接副本节点:

mongosh 192.168.88.102:27017

开启读取权限后再次执行查看文档命令
直接使用db.user.find()命令查看,会由于副本节点默认没有读取副本集内容权限而报错

> rs.secondaryOk()

Setting read preference from "primary" to "primaryPreferred"

> db.user.find()

repl_0 [direct: secondary] test> db.user.find()
[
  {
    _id: ObjectId("6536037cc9af5da41534a5bb"),
    name: 'Alice',
    age: 25,
    gender: 'female'
  }
]

可以看到同步成功

3.4 故障转移

  1. 查看MongoDB服务运行的进程
ps -ef | grep mongodb
  1. 使用kill -2 进程号命令关闭MongoDB服务进程。
  2. 登陆服务器vm2和vm3的客户端,验证这两个副本节点中是否有其中的一个节点转为主节点( MongoDB的bin目录)
  • 11
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值