Rainy Day Inn A developer's journey through life

17Feb/120

Working with Mongodb in Java with Spring-data Part 1: Configuration

Mongodb is a document-oriented NoSql (reads not-only-sql) database designed with scalability in mind.  The Spring-data project offers a nice high-level framework take makes working with mongodb easy with java.  Key feature includes:

  • Annotation based mapping between java objects and BSON data.
  • MongoTemplate which provide abstraction for mongo java driver functionalities
  • Cross store support for using mongodb together with other (Relational) database.

Current stable version is 1.0.1.Release, which address many issues with the previous releases and offer support for some new features such as atomic findAndUpdate operation.

To get started, add the following dependency to maven project:

<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-mongodb</artifactId>
 <version>1.0.1.RELEASE</version>
</dependency>

Next, create an MongoTemplate bean in Spring application context:

<mongo:mongo replica-set="localhost:27017,localhost:28017,localhost:29017">
  <mongo:options
     connections-per-host="10"
     threads-allowed-to-block-for-connection-multiplier="5"
     connect-timeout="1000"
     max-wait-time="5000"
     slave-ok="true"
     write-number="1"
     write-timeout="0"
     write-fsync="false"/>
</mongo:mongo>

<mongo:db-factory dbname="myCollection" mongo-ref="mongo"/>

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>

This example assume you have setup a three node cluster on localhost on ports 27017, 28017, 29017
A few interesting things on mongo:options:

  • replica-set: you can specify a list of servers to connect to when your application starts up.  While your application is running, if any nodes joins or leaves the cluster, the mongo driver automatically recognize the change and direct the load accordingly.
  • slave-ok: set this property to true so your application can read from slave nodes.  This is usually the setting you want.  However, in some situations where eventual consistency is not desirable, setting slave-ok to true can make sure you are only reading from the master node.
  • write-number: use this property to indicate how many nodes needs to be written to before an write operation returns. Set to 0 for non-blocking, 1 for master only, and 2+ for wait for slaves.  1 is good for most sitation, and 2+ should be used for test cases else they might fail randomly due to replication delay.
  • threads-allowed-to-block-for-connection-multiplier: for this example, 10 connections with multiplier of 5, means 50 threads is allowed to wait for connections to become free.
Be Sociable, Share!
    Comments (0) Trackbacks (0)

    No comments yet.


    Leave a comment

    Trackbacks are disabled.