Wednesday, 17 February 2016

How to implement Cache in Spring MVC.

By

This annotation is used in enabling cache support in spring MVC:

<cache:annotation-driven />

it recognize the spring cache annotations @Cacheable and@CacheEvict
Spring cache provides

@Cacheable annotation and @CacheEvict annotation.

Put @Cacheable on the method which you want to cache.
Ex: 
@Cacheable(value="messagecache", key="#id", condition="id < 10")

public String getMessage(int id)
{
  return "hello"+id;
}

Here getMessage() method is marked with @Cacheable, whenever getMessage() is called it will check the messagecache, if the data is already in messagecache it will return that otherwise it will executes the getMessage() and returns data.

@Cacheable annotations has 3 attributes

Value : is the cache name and it is mandatory, in example it is “messagecache”
Key: based on this data will be cached and it is optional
Condition:  based on the condition data will be cached. In example if the id < 10 then only data will be cached otherwise won’t. it is optional

@CacheEvict annotation will be used to delete the data from existing cache.

@CacheEvict(“employees”)

public void saveEmployee(Employee e)
{

}

Here whenever a saveEmployee() is called cache will be deleted.

@CacheEvict has 5 attributes:

Value, 2 Key, 3 condition are similar to @Cacheable, apart from these 3 we have another 2 attributes
allEntries : is a Boolean type and delete entire cache
beforeInvocation: is Boolean type and will delete the cache before the method execution
Will go through one small example:

applicationContext.xml


<!-- Scans within the base package of the application for @Components to configure as beans -->
<context:component-scan base-package="com" />

 <!-- Process cache annotations -->
<cache:annotation-driven />

<!-- Configuration for using Ehcache as the cache manager-->
<bean id="cacheManager" p:cache-manager-ref="ehcache"/>
<bean id="ehcache" p:config-location="classpath:ehcache.xml"/>

<bean id="employee" class="com.rose.ravi.model.Employee"/>
</beans>


ehcache.xml

<ehcache>
<diskStore path="java.io.tmpdir"/>
<cache name="employeeCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>

Employee pojo


public class Employee 
{
   Logger logger = LoggerFactory.getLogger(getClass());

   @Cacheable(value="employeeCache", key = "#id")
   public String getEmployee(Integer id)
   {
      logger.info("get employee called");
      return "employee"+id;
   }
}

This Employee class is injected into controller:

Controller 

@Controller
public class WebController 
{

  @Autowired
  Employee employee;

  @RequestMapping("/index.htm")

  public String homePage(@RequestParam(required= false) Integer id,   HashMap<String, String> map)
  {
    map.put("message", employee.getEmployee(id));
    return "index";
  }
}

And finally here is -
 JSP code

<body>
<h1>This is ${message }</h1>
</body>


First time for the URL : 


http://localhost:8080/springcache/index.htm?id=1

Employee class getEmployee() method will be executed and data will be placed in cache. 

second time for the same request with id=1 getEmployee() method wont be executed, this can be seen by using the log message “get employee called” prints only for the first time.
And for the


 http://localhost:8080/springcache/index.htm?id=2

getEmployee() will be called and data will be placed in cache.

Here id is the Key, if id changes method will be executed and data will be placed in cache with the key.


When ever the requests comes for the @Cacheable annotated method, spring will check the key in corresponding cache if the cache has key in it. data will be returned from the cache otherwise method will be executed.

0 comments :

Post a Comment