mongodb的replica set是一个强大的功能,可以实现读写分离功能,有heartbeat功能,可以实现自动故障转移,比master-slave更强大。
配置
主机1
保存在/etc/mongodb_1.conf1
systemLog:
path: "/var/log/mongodb/mongodb_1.log"
logAppend: true
storage:
journal:
enabled: true
dbPath: "/var/lib/mongodb_1"
processManagement:
fork: true
pidFilePath: "/var/run/mongodb/mongodb_1.pid"
net:
bindIp: 127.0.0.1
port: 27017
setParameter:
enableLocalhostAuthBypass: false
replication:
oplogSizeMB: 1000
replSetName: 'local-test'
主机2
保存在/etc/mongodb_2.conf1
systemLog:
path: "/var/log/mongodb/mongodb_2.log"
logAppend: true
storage:
journal:
enabled: true
dbPath: "/var/lib/mongodb_2"
processManagement:
fork: true
pidFilePath: "/var/run/mongodb/mongodb_2.pid"
net:
bindIp: 127.0.0.1
port: 27017
setParameter:
enableLocalhostAuthBypass: false
replication:
oplogSizeMB: 1000
replSetName: 'local-test'
主机3
保存在/etc/mongodb_3.conf1
systemLog:
path: "/var/log/mongodb/mongodb_3.log"
logAppend: true
storage:
journal:
enabled: true
dbPath: "/var/lib/mongodb_3"
processManagement:
fork: true
pidFilePath: "/var/run/mongodb/mongodb_3.pid"
net:
bindIp: 127.0.0.1
port: 27017
setParameter:
enableLocalhostAuthBypass: false
replication:
oplogSizeMB: 1000
replSetName: 'local-test'
启动
1 | mongod -f /etc/mongodb.conf mongod -f /etc/mongodb_2.conf mongod -f /etc/mongodb_3.conf |
设置
通过mongo命令,连接某一台机器,输入下面的配置命令,priority用来标示机器的优先权,优先权高的机器为primary机器,其他机器为secondary,当primary机器故障时,replica set 自动选择剩下机器中priority最高的作为primary机器。1
// 配置信息
var config = {_id:"repmore",members:[{_id:0,host:'127.0.0.1:27017',priority :2},{_id:1,host:'127.0.0.1:27018',priority:1},{_id:2,host:'127.0.0.1:27019',priority:1}]};
// replica set 初始化
rs.initiate(config);
测试
目前,通过mongo链接三台机器,会发现27017位primiary,其他为secondary。
1 | local-test:SECONDARY> rs.slaveOk() |
我们kill掉primary机器后,27018、27019会随机选择一台变为primary,因为他们两者的priority是一样的。
1 | local-test:SECONDARY> rs.status() |
mongoose链接实例
1 | 'use strict'; var mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/test', { db: { native_parser: true }, server: { poolSize: 5 }, replset: { rs_name: 'local-test' } }, function(err) { if (err) throw err; }); var Cat = mongoose.model('Cat', { name: String }); var kitty = new Cat({ name: 'Zildjian' }); kitty.save(function (err) { if (err) { console.log(err); } else { console.log('meow'); } }); Cat.findOne({}, function(err, data) { if (err) throw err; console.log(data); }); |