MongoDB 读写分离之主从配置

优点

  1. 只负责各自的写和读,极大程度的缓解X锁和S锁争用,减轻DB的负载,提升并发和吞吐
  2. 故障切换

缺点

  1. 主从延迟

场景

  1. 读多写少
  2. 至少2台服务器
  3. 数据实时性要求不高

例子
keyFile 生成参考 https://docs.mongodb.com/manual/tutorial/enforce-keyfile-access-control-in-existing-replica-set/

1主(27017)+1从(27017)+1裁判机(27018,挂载在任一服务器上, 资源消耗小)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# mongod.conf 3.4.7
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb # 裁判机 需要另设路径 /root/mongo/data/db
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0 # 允许远程连接
processManagement:
fork: true
security:
keyFile: /root/mongo/keyfile # 秘钥文件 同一个 chmod 600 keyfile
#operationProfiling:
replication:
oplogSizeMB: 2048 # 数据同步前存储空间
replSetName: rs0 # 副本集名称
#sharding:
## Enterprise-Only Options:
#auditLog:
~

步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 启动mongo
mongod --config /etc/mongod.conf

// 打开新终端,创建用户后退出
mongod --port 27017 --dbpath /var/lib/mongodb

//
service mongodb stop

//
mkdir rs0-0 rs0-1 rs0-2

// 创建mongod实例
mongod --port 27017 --dbpath /root/mongo/rs0-0 --replSet rs0 --keyFile /root/mongo/keyfile --smallfiles --oplogSize 2048 & #--oplogsize 单位M.

// 主从配置
mongo --port 27017

rsconf = {
"_id" : "rs0",
"members" : [
{
"_id" : 0,
"host" : "127.0.0.1:27017"
},
{
"_id" : 1,
"host" : "127.0.0.1:27018"
},
{
"_id" : 2,
"host" : "127.0.0.1:27019"
}
]
}

rs.initiate(rsconf);//初始化副本集就完成了
// 添加节点
rs.add(“ip:port”)
// 添加仲裁节点
rs.addArb(“ip:27018")

node 数据库连接
mongodb://username:password@ip:27017,ip:27017,ip:27018/db?replicaSet=rs0&authSource=admin

[个人网站] https://yuluhuang.com/