Connecting to the replica set to query and insert data from a Java client

In this recipe, we will demonstrate how to connect to a replica set from a Java client and how the client would automatically failover to another node in the replica set, should a primary node fail.

Getting ready

We need to take a look at the Connecting to the single node using a Java client recipe as it contains all the prerequisites and steps to set up maven and other dependencies. As we are dealing with a Java client for replica sets, a replica set must be up and running. Refer to the Starting multiple instances as part of a replica set recipe for details on how to start the replica set.

How to do it…

  1. Write/copy the following piece of code: (This Java class is also available for download from the Packt website.)
    package com.packtpub.mongo.cookbook;
    
    import com.mongodb.BasicDBObject;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.DBObject;
    import com.mongodb.MongoClient;
    import com.mongodb.ServerAddress;
    
    import java.util.Arrays;
    
    /**
     *
     */
    public class ReplicaSetMongoClient {
    
      /**
      * Main method for the test client connecting to the replica set.
       * @param args
      */
      public static final void main(String[] args) throws Exception {
        MongoClient client = new MongoClient(
          Arrays.asList(
            new ServerAddress("localhost", 27000), new ServerAddress("localhost", 27001), new ServerAddress("localhost", 27002)
          )
        );
        DB testDB = client.getDB("test");
        System.out.println("Dropping replTest collection");
        DBCollection collection = testDB.getCollection("replTest");
        collection.drop();
        DBObject object = new BasicDBObject("_id", 1).append("value", "abc");
        System.out.println("Adding a test document to replica set");
        collection.insert(object);
        System.out.println("Retrieving document from the collection, this one comes from primary node");
        DBObject doc = collection.findOne();
        showDocumentDetails(doc);
        System.out.println("Now Retrieving documents in a loop from the collection.");
        System.out.println("Stop the primary instance after few iterations ");
        for(int i = 0 ; i < 10; i++) {
          try {
            doc = collection.findOne();
            showDocumentDetails(doc);
          }
          catch (Exception e) {
            //Ignoring or log a message
          }
          Thread.sleep(5000);
        }
      }
    
      /**
      *
      * @param obj
      */
      private static void showDocumentDetails(DBObject obj) {
        System.out.printf("_id: %d, value is %s
    ", obj.get("_id"), obj.get("value"));
      }
    }
  2. Connect to any of the nodes in the replica set, say to localhost:27000, and execute rs.status() from the shell. Take a note of the primary instance in the replica set and connect to it from the shell if localhost:27000 is not a primary. Here, switch to the administrator database as follows:
    repSetTest:PRIMARY>use admin
    
  3. We now execute the preceding program from the operating system shell as follows:
    $ mvn compile exec:java -Dexec.mainClass=com.packtpub.mongo.cookbook.ReplicaSetMongoClient
    
  4. Shut down the primary instance by executing the following on the mongo shell that is connected to the primary:
    repSetTest:PRIMARY> db.shutdownServer()
    
  5. Watch the output on the console where the com.packtpub.mongo.cookbook.ReplicaSetMongoClient class is executed using maven.

How it works…

An interesting thing to observe is how we instantiate the MongoClient instance. It is done as follows:

  MongoClient client = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27000), new ServerAddress("localhost", 27001), new ServerAddress("localhost", 27002)));

The constructor takes a list of com.mongodb.ServerAddress. This class has a lot of overloaded constructors but we choose to use the one that takes the hostname and then port. What we have done is provided all the server details in a replica set as a list. We haven't mentioned what is the PRIMARY node and what are the SECONDARY nodes. MongoClient is intelligent enough to figure this out and connect to the appropriate instance. The list of servers provided is called the seed list. It need not contain an entire set of servers in a replica set though the objective is to provide as much as we can. MongoClient will figure out all the server details from the provided subset. For example, if the replica set is of five nodes but we provide only three servers, it works fine. On connecting with the provided replica set servers, the client will query them to get the replica set metadata and figure out the rest of the provided servers in the replica set. In the preceding case, we instantiated the client with three instances in the replica set. If the replica set was to have five members, then instantiating the client with just three of them is still good enough and the remaining two instances will be automatically discovered.

Next, we start the client from the command prompt using maven. Once the client is running in the loop, we bring down the primary instance to find one document. We should see something as the following output to the console:

_id: 1, value is abc
Now Retrieving documents in a loop from the collection.
Stop the primary instance manually after few iterations
_id: 1, value is abc
_id: 1, value is abc
Nov 03, 2013 5:21:57 PM com.mongodb.ConnectionStatus$UpdatableNode update
WARNING: Server seen down: Amol-PC/192.168.1.171:27002
java.net.SocketException: Software caused connection abort: recv failed
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.read(SocketInputStream.java:150)

WARNING: Primary switching from Amol-PC/192.168.1.171:27002 to Amol-PC/192.168.1.171:27001
_id: 1, value is abc

As we can see, the query in the loop was interrupted when the primary node went down. However, the client switched to the new primary seamlessly. Well, nearly seamlessly, as the client might have to catch an exception and retry the operation after a predetermined interval has elapsed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset