Home Database Mysql Tutorial mongodb replica set 多服务器 高可用 配置 详解

mongodb replica set 多服务器 高可用 配置 详解

Jun 07, 2016 pm 04:33 PM
mongodb set Available server High availability

mongodb的多服务器配置,以前写过一篇文章,是master-slave模式的,请参考: mongodb 主从 配置 详解 。master-slave模式,不能自动实现故障转移和恢复。所以推荐大家使用mongodb的replica set,来实现多服务器的高可用。给我的感觉是replica set好像自带了h

mongodb的多服务器配置,以前写过一篇文章,是master-slave模式的,请参考:mongodb 主从 配置 详解。master-slave模式,不能自动实现故障转移和恢复。所以推荐大家使用mongodb的replica set,来实现多服务器的高可用。给我的感觉是replica set好像自带了heartbeat功能,挺强大的。

一,三台服务器,1主,2从

服务器1:127.0.0.1:27017

服务器2:127.0.0.1:27018

服务器3:127.0.0.1:27019

1,创建数据库目录

[root@localhost ~]# mkdir /var/lib/{mongodb_2,mongodb_3}
Copy after login

在一台机子上面模拟,三台服务器,所以把DB目录分开了。

2,创建配置文件

[root@localhost ~]# cat /etc/mongodb.conf |awk '{if($0 !~ /^$/ && $0 !~ /^#/) {print $0}}'  //主服务器配置
port = 27017        //监听端口
fork = true         //后台运行
pidfilepath = /var/run/mongodb/mongodb.pid    //进程PID文件
logpath = /var/log/mongodb/mongodb.log        //日志文件
dbpath =/var/lib/mongodb           //db存放目录
journal = true                   //存储模式
nohttpinterface = true           //禁用http
directoryperdb=true              //一个数据库一个文件夹
logappend=true                  //追加方式写日志
replSet=repmore                 //集群名称,自定义
oplogSize=1000                  //oplog大小
[root@localhost ~]# cat /etc/mongodb_2.conf |awk '{if($0 !~ /^$/ && $0 !~ /^#/) {print $0}}'  //从服务器
port = 27018
fork = true
pidfilepath = /var/run/mongodb/mongodb_2.pid
logpath = /var/log/mongodb/mongodb_2.log
dbpath =/var/lib/mongodb_2
journal = true
nohttpinterface = true
directoryperdb=true
logappend=true
replSet=repmore
oplogSize=1000
[root@localhost ~]# cat /etc/mongodb_3.conf |awk '{if($0 !~ /^$/ && $0 !~ /^#/) {print $0}}'  //从服务器
port = 27019
fork = true
pidfilepath = /var/run/mongodb/mongodb_3.pid
logpath = /var/log/mongodb/mongodb_3.log
dbpath =/var/lib/mongodb_3
journal = true
nohttpinterface = true
oplogSize = 1000
directoryperdb=true
logappend=true
replSet=repmore
Copy after login

在这里要注意一点,不要把认证开起来了,不然查看rs.status();时,主从服务器间,无法连接,"lastHeartbeatMessage" : "initial sync couldn't connect to 127.0.0.1:27017"

3,启动三台服务器

mongod -f /etc/mongodb.conf
mongod -f /etc/mongodb_2.conf
mongod -f /etc/mongodb_3.conf
Copy after login

注意:初次启动时,主服务器比较快的,从服务器有点慢。

二,配置并初始化replica set

1,配置replica set节点

> 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}]}
Copy after login

2,初始化replica set

> rs.initiate(config);
{
    "info" : "Config now saved locally.  Should come online in about a minute.",
    "ok" : 1
}
Copy after login

3,查看replica set各节点状态

repmore:PRIMARY> rs.status();
{
    "set" : "repmore",
    "date" : ISODate("2013-12-16T21:01:51Z"),
    "myState" : 2,
    "syncingTo" : "127.0.0.1:27017",
    "members" : [
        {
            "_id" : 0,
            "name" : "127.0.0.1:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 33,
            "optime" : Timestamp(1387227638, 1),
            "optimeDate" : ISODate("2013-12-16T21:00:38Z"),
            "lastHeartbeat" : ISODate("2013-12-16T21:01:50Z"),
            "lastHeartbeatRecv" : ISODate("2013-12-16T21:01:50Z"),
            "pingMs" : 0,
            "syncingTo" : "127.0.0.1:27018"
        },
        {
            "_id" : 1,
            "name" : "127.0.0.1:27018",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 1808,
            "optime" : Timestamp(1387227638, 1),
            "optimeDate" : ISODate("2013-12-16T21:00:38Z"),
            "errmsg" : "syncing to: 127.0.0.1:27017",
            "self" : true
        },
        {
            "_id" : 2,
            "name" : "127.0.0.1:27019",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 1806,
            "optime" : Timestamp(1387227638, 1),
            "optimeDate" : ISODate("2013-12-16T21:00:38Z"),
            "lastHeartbeat" : ISODate("2013-12-16T21:01:50Z"),
            "lastHeartbeatRecv" : ISODate("2013-12-16T21:01:51Z"),
            "pingMs" : 0,
            "lastHeartbeatMessage" : "syncing to: 127.0.0.1:27018",
            "syncingTo" : "127.0.0.1:27018"
        }
    ],
    "ok" : 1
}
Copy after login

在这里要注意,rs.initiate初始化也是要一定时间的,刚执行完rs.initiate,我就查看状态,从服务器的stateStr不是SECONDARY,而是stateStr" : "STARTUP2",等一会就好了。

三,replica set主,从测试

1,主服务器测试

repmore:PRIMARY> show dbs;
local    1.078125GB
repmore:PRIMARY> use test
switched to db test
repmore:PRIMARY> db.test.insert({'name':'tank','phone':'12345678'});
repmore:PRIMARY> db.test.find();
{ "_id" : ObjectId("52af64549d2f9e75bc57cda7"), "name" : "tank", "phone" : "12345678" }
Copy after login

2,从服务器测试

[root@localhost mongodb]# mongo 127.0.0.1:27018   //连接
MongoDB shell version: 2.4.6
connecting to: 127.0.0.1:27018/test
repmore:SECONDARY> show dbs;
local    1.078125GB
test    0.203125GB
repmore:SECONDARY> db.test.find();     //无权限查看
error: { "$err" : "not master and slaveOk=false", "code" : 13435 }
repmore:SECONDARY> rs.slaveOk();       //从库开启
repmore:SECONDARY> db.test.find();     //从库可看到主库刚插入的数据
{ "_id" : ObjectId("52af64549d2f9e75bc57cda7"), "name" : "tank", "phone" : "12345678" }
repmore:SECONDARY> db.test.insert({'name':'zhangying','phone':'12345678'});   //从库只读,无插入权限
not master
Copy after login

到这儿,我们的replica set就配置好了。

四,故障测试

前面我说过,mongodb replica set有故障转移功能,下面就模拟一下,这个过程

1,故障转移

1.1,关闭主服务器

[root@localhost mongodb]# ps aux |grep mongod    //查看所有的mongod
root     16977  0.2  1.1 3153692 44464 ?       Sl   04:31   0:02 mongod -f /etc/mongodb.conf
root     17032  0.2  1.1 3128996 43640 ?       Sl   04:31   0:02 mongod -f /etc/mongodb_2.conf
root     17092  0.2  0.9 3127976 38324 ?       Sl   04:31   0:02 mongod -f /etc/mongodb_3.conf
root     20400  0.0  0.0 103248   860 pts/2    S+   04:47   0:00 grep mongod
[root@localhost mongodb]# kill 16977  //关闭主服务器进程
[root@localhost mongodb]# ps aux |grep mongod
root     17032  0.2  1.1 3133124 43836 ?       Sl   04:31   0:02 mongod -f /etc/mongodb_2.conf
root     17092  0.2  0.9 3127976 38404 ?       Sl   04:31   0:02 mongod -f /etc/mongodb_3.conf
root     20488  0.0  0.0 103248   860 pts/2    S+   04:47   0:00 grep mongod
Copy after login

1.2,在主库执行命令

repmore:PRIMARY> show dbs;
Tue Dec 17 04:48:02.392 DBClientCursor::init call() failed
Copy after login

1.3,从库查看状态,如下图,

replica set 故障测试

replica set 故障测试

以前的从库变主库了,故障转移成功

2,故障恢复

mongod -f /etc/mongodb.conf
Copy after login

启动刚被关闭的主服务器,然后在登录到主服务器,查看状态rs.status();已恢复到最原始的状态了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Which version is generally used for mongodb? Which version is generally used for mongodb? Apr 07, 2024 pm 05:48 PM

It is recommended to use the latest version of MongoDB (currently 5.0) as it provides the latest features and improvements. When selecting a version, you need to consider functional requirements, compatibility, stability, and community support. For example, the latest version has features such as transactions and aggregation pipeline optimization. Make sure the version is compatible with the application. For production environments, choose the long-term support version. The latest version has more active community support.

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

How to configure Dnsmasq as a DHCP relay server How to configure Dnsmasq as a DHCP relay server Mar 21, 2024 am 08:50 AM

The role of a DHCP relay is to forward received DHCP packets to another DHCP server on the network, even if the two servers are on different subnets. By using a DHCP relay, you can deploy a centralized DHCP server in the network center and use it to dynamically assign IP addresses to all network subnets/VLANs. Dnsmasq is a commonly used DNS and DHCP protocol server that can be configured as a DHCP relay server to help manage dynamic host configurations in the network. In this article, we will show you how to configure dnsmasq as a DHCP relay server. Content Topics: Network Topology Configuring Static IP Addresses on a DHCP Relay D on a Centralized DHCP Server

Where is the database created by mongodb? Where is the database created by mongodb? Apr 07, 2024 pm 05:39 PM

The data of the MongoDB database is stored in the specified data directory, which can be located in the local file system, network file system or cloud storage. The specific location is as follows: Local file system: The default path is Linux/macOS:/data/db, Windows: C:\data\db. Network file system: The path depends on the file system. Cloud Storage: The path is determined by the cloud storage provider.

What should I do if I can't enter the game when the epic server is offline? Solution to why Epic cannot enter the game offline What should I do if I can't enter the game when the epic server is offline? Solution to why Epic cannot enter the game offline Mar 13, 2024 pm 04:40 PM

What should I do if I can’t enter the game when the epic server is offline? This problem must have been encountered by many friends. When this prompt appears, the genuine game cannot be started. This problem is usually caused by interference from the network and security software. So how should it be solved? The editor of this issue will explain I would like to share the solution with you, I hope today’s software tutorial can help you solve the problem. What to do if the epic server cannot enter the game when it is offline: 1. It may be interfered by security software. Close the game platform and security software and then restart. 2. The second is that the network fluctuates too much. Try restarting the router to see if it works. If the conditions are OK, you can try to use the 5g mobile network to operate. 3. Then there may be more

What are the advantages of mongodb database What are the advantages of mongodb database Apr 07, 2024 pm 05:21 PM

The MongoDB database is known for its flexibility, scalability, and high performance. Its advantages include: a document data model that allows data to be stored in a flexible and unstructured way. Horizontal scalability to multiple servers via sharding. Query flexibility, supporting complex queries and aggregation operations. Data replication and fault tolerance ensure data redundancy and high availability. JSON support for easy integration with front-end applications. High performance for fast response even when processing large amounts of data. Open source, customizable and free to use.

What does mongodb mean? What does mongodb mean? Apr 07, 2024 pm 05:57 PM

MongoDB is a document-oriented, distributed database system used to store and manage large amounts of structured and unstructured data. Its core concepts include document storage and distribution, and its main features include dynamic schema, indexing, aggregation, map-reduce and replication. It is widely used in content management systems, e-commerce platforms, social media websites, IoT applications, and mobile application development.

How to install PHP FFmpeg extension on server? How to install PHP FFmpeg extension on server? Mar 28, 2024 pm 02:39 PM

How to install PHPFFmpeg extension on server? Installing the PHPFFmpeg extension on the server can help us process audio and video files in PHP projects and implement functions such as encoding, decoding, editing, and processing of audio and video files. This article will introduce how to install the PHPFFmpeg extension on the server, as well as specific code examples. First, we need to ensure that PHP and FFmpeg are installed on the server. If FFmpeg is not installed, you can follow the steps below to install FFmpe

See all articles