Scaling your Java Spring Applications with Distributed Cache

Spring is a popular lightweight dependency injection and aspect oriented development container and framework for Java. It reduces the overall complexity of J2EE development and provides high cohesion and loose coupling. Because of the benefits Spring provides, it is used by a lot of developers for creating high traffic small to enterprise level applications.

Here is an example of a Spring Java application:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MySampleApp {
   …
 ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
     //In spring.xml
 Department dept = (Department) ctx.getBean"department");

 List employees = dept.getEmployees();
   for(int i=0; i< employees.size();i++)
   {
      Employee emp = employees.get(i);
      System.out.println("Student Name :"student.getName());
   }
   …
 }

But, these high traffic Spring applications face a major scalability problem. Although these applications can scale by adding more servers to the application server farm, their database server cannot scale in the same fashion to handle the growing transactional load.

In such situations, a Java distributed cache is your best bet to handle the database scalability problem. Java distributed cache offloads your database by reducing those expensive database trips that are causing scalability bottlenecks. And, it also improves your application performance by serving data from in-memory cache store instead of the database.

NCache is a Java distributed cache and has implemented the Spring cache provider. NCache Spring provider introduces a generic Java cache mechanism with which you can easily cache the output of your CPU intensive, time consuming, and database bound methods of Spring application. This approach not only reduces the database load but also reduces the number of method executions and improves application performance.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

NCache Spring provider has a set of annotations including @Cacheable to handle cache related tasks. Using these annotations you can easily mark the method required to be cached along with cache expiration, key generation and other strategies.

When a Spring method marked as @Cacheable is invoked, NCache checks the cache storage to verify whether the method has already been executed with the given set of parameters or not. If it has, then the results are returned from the cache. Otherwise, method is executed and its results are also cached. That is how, expensive CPU, I/O and database bound methods are executed only once and their results are reused without actually executing the method.

Java distributed cache is essentially a key-value store, therefore each method innovation should translate to a suitable unique key for the access. To generate these cache keys NCache Spring provider uses the combination of class name, method and arguments. However, you can also implement your custom NCache Spring key generator by using com.alachisoft.ncache.annotations.key.CacheKeyGenerator interface.

Here are the steps to integrate NCache cache provider in your application: 

  1. Add Cache Annotations: Add NCache Spring annotation to methods which require caching. Here is a sample of Spring method using NCache annotation:
  2. @Cacheable
     (cacheID="r2-DistributedCache",
      slidingExpirator = @SlidingExpirator (expireAfter=15000)
     )
     public Collection<Message>; findAllMessages()
     {
    	...
          Collection<Message> values = messages.values();
    	Set<Message> messages = new HashSet<Message>();
    	synchronized (messages) {
    		Iterator<Message> iterator = values.iterator();
    		while (iterator.hasNext()) {
    			messages.add(iterator.next());
    		}
    	}
    	...
       return Collections.unmodifiableCollection(messages);
     	}
    
    
  3. Register NCache Spring Provider:  Update your Spring application spring.xml to register NCache Spring provider as follows:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:ncache="http://www.alachisoft.com/ncache/annotations/spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.alachisoft.com/ncache/annotations/spring http://www.alachisoft.com/ncache/annotations/spring/ncache-spring-1.0.xsd">

<ncache:annotation-driven>
        <ncache:cache id="r1-LocalCache" name="myCache"/>
        <ncache:cache id="r2-DistributedCache" name="myDistributedCache"/>
   </ncache:annotation-driven>

Hence, by using NCache Spring cache provider you can scale your Spring applications linearly and can boost performance.

So, download a fully working 60-day trial of NCache Enterprise and try it out for yourself.

Download NCache Trial | NCache Details

This entry was posted in Distributed Cache, Spring and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


five − = 3

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>