MongoDB replica set implementation and read-write separation

Source: Internet
Author: User
Tags mongoclient mongodb server

In the previous article "MongoDB Master-Slave Model Building Example", we have a simple introduction to how to build a master-slave architecture of the MONGODB server environment. However, for the master-slave structure, MONGODB officials do not recommend that we use, probably because the master-slave mode has the following two disadvantages:

(1) After the primary node is not available, it cannot automatically switch to the slave node and cannot ensure the uninterrupted operation of the business access;

(2) All the read and write operations are to the main node, resulting in a large access pressure on the main node;

As a result, MongoDB provides us with another recommended way of using replica set replicasets. This article briefly describes how the replica set is implemented, and how to solve the above two problems.


First we build a replica set (because there are not so many server machines, which are used on a single machine, using different port numbers to simulate MongoDB instances on different machines).


The first step: We start three different MongoDB instances on the 1111, 2222 and 33,333 ports on this machine;

Mongod--port 1111--dbpath f:/mongodb1/data/db--logpath f:/mongodb1/data/log/mongodb.log--replSet test--logappend
Mongod--port 2222--dbpath f:/mongodb2/data/db--logpath f:/mongodb2/data/log/mongodb.log--replSet test--logappend
Mongod--port 3333--dbpath f:/mongodb3/data/db--logpath f:/mongodb3/data/log/mongodb.log--replSet test--logappend

Here we launch three MongoDB instances, and specify the corresponding data directory and log directory, it is necessary to note that the MongoDB instance is a node in the replica set, and the name of the replica set is test.--replset.


Step two: Log on to an instance, write instructions, combine three different MongoDB instances together to form a complete replica set;

config_test={"_id": "Test", members:[
{_id:0,host: "127.0.0.1:1111"},
{_id:1,host: "127.0.0.1:2222"},
{_id:2,host: "127.0.0.1:3333"},
]};
Here, members can contain multiple values, which are listed here are the three MongoDB instances that were just started, and the copy set was named Test by the _id field.


Step three: Initialize the replica set by executing the following command.

Rs.initiate (config_test);

This uses the above configuration to initialize the MongoDB replica set.


With the three steps above, you can simply build a copy set named Test that consists of three MongoDB instances. If you want to see the status of the replica set, you can use the Rs.status () command to view it.


The replica sets are now set up, so can this replica set solve two of the problems we have in the master and slave modes above?


Let's start with the first question, we'll turn off the 1111-Port MongoDB server, and then we'll use the Rs.status () command to look under as follows:



Here, a brief description of the individual fields in the return information is required, health indicates whether the node is normal in the replica set, 0 is unhealthy, 1 is normal, the state represents the identity of the node, 0 represents a non-primary node, and 1 represents the primary node; Statestr is used to describe the identity of the node. Primary represents the primary node, secondary represents the secondary node; name is the IP and port information for the replica set node, and so on.


From the return package information, you can see that when the 1111 port is closed, the node is unreachable in the state of the replica set node, and a re-selection of the resulting primary node is the MongoDB instance started on port 3333, as for the selected process in the following article, here is a simple point, when the primary node hangs, Other nodes can initiate an election, so long as a node obtains more than half of the number of copies of the replica set node in the election process and no node votes against it, the node can become the primary node.


After the MongoDB instance on port 1111 is hung, the first problem is resolved by the automatic switchover of 3,333 for the new master node.


As for the second problem, that is, the master node is responsible for all the read and write operations causing the main node pressure is large, then how to solve this problem in the replica set? Under normal circumstances, we access the replica set in Java as follows:

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;"  >public class Testmongodbreplset {public static void main (string[] args) {try {list<serveraddress> addresses =              New Arraylist<serveraddress> (); ServerAddress Address1 = new ServerAddress ("127.0.0.1", 1111); ServerAddress address2 = new ServerAddress ("127.0.0.1", 2222); ServerAddress ADDRESS3 = new ServerAddress ("127.0.0.1", 3333);              Addresses.add (ADDRESS1); Addresses.add (ADDRESS2); Addresses.add (ADDRESS3); Mongoclient client = new Mongoclient (addresses); DB db = Client.getdb ("test"); Dbcollection coll = db.getcollection ("test");              Insert Basicdbobject object = new Basicdbobject (); Object.append ("Key1", "value1"); Coll.insert (object); Dbcursor dbcursor = Coll.find ();                  while (Dbcursor.hasnext ()) {DBObject dbobject = Dbcursor.next (); System. Out.println (Dbobject.tostring ());          }} catch (Exception e) {e.printstacktrace (); }}} </span>

However, it is not possible to read and write pressure dispersion in the replica set, in fact, at the code level, we can set the second access to the replica set when the data only from the secondary node. The replica set reads and writes the detach structure as shown:


In order to implement read-write separation on the replica set, we need to implement the following two steps:

(1) Set the Setslaveok on the replica node;

(2) At the code level, set the read data from the replica node during the read operation as follows:


<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;"  >public class Testmongodbreplset {public static void main (string[] args) {try {list<serveraddress> addresses =              New Arraylist<serveraddress> (); ServerAddress Address1 = new ServerAddress ("127.0.0.1", 1111); ServerAddress address2 = new ServerAddress ("127.0.0.1", 2222); ServerAddress ADDRESS3 = new ServerAddress ("127.0.0.1", 3333);              Addresses.add (ADDRESS1); Addresses.add (ADDRESS2); Addresses.add (ADDRESS3); Mongoclient client = new Mongoclient (addresses); DB db = Client.getdb ("test"); Dbcollection coll = db.getcollection ("test");              Basicdbobject object = new Basicdbobject (); Object.append ("Key1", "value1");  Readpreference preference = Readpreference.secondary ();  DBObject DBObject = Coll.findone (object, null, preference); System.  Out. println (DBObject);          } catch (Exception e) {e.printstacktrace (); }}} </span>


There are several other parameters that can be used in addition to secondary reading parameters, and their meanings are as follows:

Primary: The default parameter, only read from the primary node;
Primarypreferred: Most of the data is read from the primary node, and the data is read from the secondary node only when the primary node is unavailable.
Secondary: Only read from the secondary node, the problem is that the data of the secondary node is "old" than the primary node data.
Secondarypreferred: read from the secondary node, and read data from the master node when the secondary node is unavailable;
Nearest: Reads data from the node with the lowest network latency, whether it is the primary node or the secondary node.


This enables the separation of reads and writes on the replica set, and solves the second problem mentioned in the article above. As for the other important part of the replica set, how is the master-slave data synchronized? How do I elect to generate a new master node? How do the individual nodes in the replica set synchronize information? These questions, will be another article to describe, such as dare to interest, you can follow my blog, thank you. ^_^

MongoDB replica set implementation and read-write separation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.