Alachisoft NCache 4.1 - Online Documentation

Enabling NCache in Spring Framework Applications

 
NCache is providing support for Spring framework applications. Now users can cache spring applications data using NCache to enhance performance of the application. Few changes are required in deployment descriptor file (which comes with your spring application) to plug-in NCache as your cache provider and you're all set to start using distributed caching.
 
Following are the prerequisites to enable NCache in Spring application:
 
1. You should have a Spring framework application. You can also use sample application for Spring from the following path:
 
"Installeddirectory:/NCache/samples/java/NetBeans/NCacheSpringTest"
 
  • In every Spring application, Spring Deployment Descriptor already exists with the xml extension.
 
2. NCache Java Client for:
 
  • NCacheSpringAnnotation.jar
  • NCClient.jar
  • NCActivate.jar
  • NCRuntime.jar
  • NCSerialization.jar
 
Following are the steps required to enable NCache in Spring application:
 
 
Step 1: Add Library:
 
Add "NCacheSpringAnnotation.jar" library to your Spring application. This .jar file is placed at the following path:
 
          "Installeddirectory:/NCache/integration/java/spring".
 
After adding library, changes are required in 2 different files:
 
 
Step 2: Spring Deployment Descriptor Configurations:
 
Spring Deployment Descriptor already exist in a spring application, following changes are required to be made in this file:
 
1. Here you need to add the following elements as shown below:
 
[Existing Schema]
 
<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"
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">
 
In order to inject NCache Spring Provider, you need to add the following two highlighted attributes in the existing schema.
 
  • Add xmlns:ncache attribute with its value in the schema.
  • Concatenate the NCache location in xsi:schemaLocation with the already existing location fields, as shown below:
 
[Changed Schema]
 
<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">
 
2. In Spring Deployment Descriptor, add the following element:
 
        <ncache:annotation-driven>
            <ncache:cache id="ID-1" name="mycache"/>
            <ncache:cache id="ID-2" name="myreplicatedcache"/>
        </ncache:annotation-driven>
 
"NCache:annotation-driven" tag provides the facility to add number of caches to be used with Spring framework application.
 
 
Step 3: Application Level Changes:
 
NCache provides number of annotation to perform various cache related tasks. You only need to add those annotations on the top of your methods to perform those tasks.
 

1. Key Generator:
 
Key Generator annotation is used to generate keys for caching spring application data in the cache. Here any of the two methods can be used to generate key for caching data. This annotation can be applicable to both @cacheable and @triggersremove.

 
a. Default method:
 
Default key generator includes a class name, method name and a list of arguments a method contains. By default method name is included in the key but you can omit the method name from the key by setting value="false" as shown below:
 
    @Cacheable
        (
            cacheID="ID-1",
            keyGenerator = @KeyGenerator (properties = @Property(name="includeMethod", value="false")))
      
    public Collection<Message> findAllMessages()
      {
        .....
      }
 
 
b. Custom Class:
 
NCache is providing you the facility to have your own custom class for key generation. In this way, you can generate keys in number of flexible ways which meet your business requirements. NCache provides an interface “CacheKeyGenerator” for defining your own key generation technique. All you need to do is to implement “CacheKeyGenerator” interface and override its “generateKey” method.
 
Below is how your class looks like:
 
public class MyKeyGenerator implements CacheKeyGenerator
{
    public String generateKey(MethodInvocation methodInvocation)
    {
        return String;
    }
}
 
You need to register your custom class for key generator as beans in spring deployment descriptor using the following xml:
 
<bean id="MyKeyGenerator" class="NCacheSpringTest.CustomKeyGenerators.MyKeyGenerator" />
 
Below is the code for calling your custom class for key generation in any annotation:
 
@Cacheable(cacheID="ID-1", keyGenerator = @KeyGenerator (name="MyKeyGenerator" ) )
 
      public Collection<Message> findAllMessages()
      {
        .....
      }
 

2. Sliding Expiration:
 
SlidingExpiration is use to expire the data (returns by the method) from the cache after a specific period of time. It will remove key from the cache if the specified period of time has elapsed since it was last accessed. This annotation is only applicable with @cacheable annotation.
 
 
For example:
 
        @Cacheable
        (
            cacheID="ID-1",
            slidingExpirator = @SlidingExpirator (expireAfter=15000)
        )
  public Collection<Message> findAllMessages()
  {
    .....
  }
   

3. Partial Cache Key:
 
PartialCacheKey annotation is used with the default process of key generation. Here, it filters out arguments with which this annotation is appended and include them in the process of key generation while excluding the remaining arguments. PartialCacheKey can be applicable to both attributes of an object and parameters of a method. Here users are supposed to put this annotation before particular attribute/parameter as shown below:
 
For example:
 
        @TriggersRemove
        (
            cacheID="ID-1",
            when = When.BEFORE_METHOD_INVOCATION,
            removeAll = false,
            keyGenerator = @KeyGenerator(properties = @Property(name="includeMethod", value="false"))
        )
 
        public void updateMessage(@PartialCacheKey long id, String to, String body)
        {
          ......
        }
 

4. Cacheable:
 
The purpose of this annotation is to cache the data returned by the method with a specific key. Before caching the data, @cacheable generates a method specific key according to the given specifications and cache the data against that key. Here users are supposed to specify a cache id where they are interested to cache data of the method. This annotation is applicable to the methods of a class.
 
For example:
 
@Cacheable
(
    cacheID="ID-1"   
)
 
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);
}
 

5. Triggers Remove:
 
As mentioned above, a specific key is required to cache the data of the method. This annotation follows the same procedure for removing the data of a method by generating a similar key with which it is added.  The purpose of @triggersremove annotation is to remove the data of a method from the cache by matching the key with the cached keys. To remove data from the cache you need to specify the following attributes:
 
  • CacheID: Specify the cache id from where the data is to be removed.
 
  • When: It will specify either the data is removed before or after the execution of a method. It take two different values i.e. When.AFTER_METHOD_INVOCATION and When.BEFORE_METHOD_INVOCATION.
 
  • RemoveAll: If value of this attribute is "False", it will only remove data of a specific key. If value is "True", it will clear the cache and remove all class related data from the cache.
 
This annotation is applicable to the methods of a class. 
 
For example:
 
        @TriggersRemove
        (
            cacheID="ID-1",
            when = When.BEFORE_METHOD_INVOCATION,
            removeAll = false          
        )
 
        public void updateMessage(long id, String to, String body)
        {
                Message message = new Message();
                message.setId(id);
                message.setTo(to);
                message.setBody(body);
                messages.remove(id);
                      messages.put(id, message);
        }
 
 
Note:
You can cache values of two different methods of a class in two different caches.
Two similar annotations can't be used on top of the same method.
You can not run @TriggersRemove for two caches on top of same method.
 
 
 
See Also
 

 
Copyright © 2005-2012 Alachisoft. All rights reserved.