persistent disk storage in ehcache

Requirement – To have persistent storage in ehcahce

Solution-
cacheManagerPeerProviderFactory –It is used for saying “Hello, I’m here!” and allows to discover the other CacheManager in the cluster and be discovered by other nodes.

It accepts only two arguments (class and properties).

cacheEventListenerFactory — It is used for receiving notification about cache update by other nodes in cache cluster.

bootstrapCacheLoaderFactory —It is used for starting cache system and synchronize the cached elements in the cluster.

package com.techartifact.caching;

import java.util.ArrayList;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

// this is main class.
public class MainClass {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MainClass mainClass = new MainClass();
		mainClass.runMainClass();
	}

	private void runMainClass() {
		// TODO Auto-generated method stub
		int TOTAL=3;
	         CacheManager cacheManager = new CacheManager();
		Cache myCache = cacheManager.getCache("persistentEhcacheNew");

		System.out.println("the size of my cache at startup is: "+myCache.getSize());
		System.out.println("disk store size: "+myCache.getDiskStoreSize());
		System.out.println("memory store size: "+myCache.getMemoryStoreSize());
	        System.out.println("memory DiskStoreSize size: "+myCache.getDiskStoreSize());
	        System.out.println("boot strapCacheLoader is Asynchronous: "+myCache.getBootstrapCacheLoader().isAsynchronous());
                System.out.println("cache status: "+myCache.getStatus());
	        System.out.println("cache name: "+myCache.getName());
                List listOfKeys= myCache.getKeys();
                //myCache.removeAll();
                if(myCache.getDiskStoreSize()>0){
               for (Object temp : listOfKeys) {
                        System.out.println((String)temp.toString());
	                Element element = myCache.get(temp);  
	                     
	                      if (element != null) {  
	                       System.out.println(temp + " is in the cache!!!"); 
	                       String val = (String)element.getValue().toString();
                               System.out.println(val + " value is in the cache!!!");
                              }
	            }
                }else{
              
		System.out.println("now add 3 elements to cache");
                    for (int i = 0; i < TOTAL; i++) {
                            DataObject dataObject = new DataObject();
                           dataObject.setRandomFloat(Randomizer.returnRandomFloat());
                            dataObject.setRandomString(Randomizer.returnRandomString());			
                            Element element = new Element(i,  dataObject.getRandomFloat());
                            myCache.put(element);
                   }
                }

		cacheManager.shutdown();
		
	}

}


BootstrapCacheLoaderFactory – An abstract factory for creating BootstrapCacheLoader instances. Implementers should provide their own concrete factory extending this factory. It can then be configured in ehcache.xml.

Create a MyBootstrapCacheLoaderFactory that extends BootStrapCacheLoaderFactory, and override method load(EhCache ehcacheparam)to bring the cache up on server startup

package com.techartifact.caching;

import java.util.List;
import java.util.Properties;

import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.bootstrap.BootstrapCacheLoader;
import net.sf.ehcache.bootstrap.BootstrapCacheLoaderFactory;

// 
public class MyBootstrapCacheLoaderFactory extends BootstrapCacheLoaderFactory implements BootstrapCacheLoader{
	

	@Override
	public BootstrapCacheLoader createBootstrapCacheLoader(Properties properties) {
		// TODO Auto-generated method stub
		return new MyBootstrapCacheLoaderFactory();
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return super.clone();
	}
	public boolean isAsynchronous() {
		// TODO Auto-generated method stub
		return false;
	}
	public void load(Ehcache myCache) throws CacheException {
		// TODO Auto-generated method stub
		System.out.println("load your cache with whatever you want....");
		List keys = myCache.getKeys();
		for (int i = 0; i < keys.size(); i++) {
			Element element = myCache.get((keys.get(i).toString()));
		}
		System.out.println("load complete!");
	}



}

Ehcache SimplePageCachingFilter

Add caching layer on your web application, with out modifying the code.

SimplePageCachingFilter

Ehcache has an out-of-box of solution for this ‘SimplePageCachingFilter’.
SimplePageCachingFilter is caching filter can be use full for html or any other response type
e.g JSON or xml. It uses singleton Ehcache manager to store contents. Cache keys are calculated
using the URI and query string. /exampleData?user=admin&role=admin.

There is another variant of ‘SimplePageCachingFilter’ based on headers ‘SimpleCachingHeadersPageCachingFilter’.
This filter take account headers for cache key. It take three account of headers

  • ETag
  • Last-Modified
  • Expires

Configuration

cacheName
Cache used by filter for storing content

blockingTimeoutMillis
the time, in milliseconds, to wait for the filter chain to return with a response on a cache miss. This is useful to fail fast in the event of an infrastructure failure.

varyHeader
set to true to set Vary:Accept-Encoding in the response when doing Gzip. This header is needed to support HTTP proxies however it is off by default.

Web.xml

<filter>
<filter-name>SimplePageCachingFilter</filter-name>
 <filter-class>net.sf.ehcache.constructs.web.filter.
SimplePageFragmentCachingFilter
 </filter-class>
 <init-param>
  <param-name>cacheName</param-name>
  <param-value>simplePageCache</param-value>
 </init-param>
</filter>
<filter-mapping>
<filter-name>SimplePageCachingFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

Ehcache configuration

<Ehcachexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../main/config/ehcache.xsd">
<diskStorepath="java.io.tmpdir"/>
 <defaultCache
   maxEntriesLocalHeap="10"
   eternal="false"
   timeToIdleSeconds="5"
   timeToLiveSeconds="10"
   overflowToDisk="true"
   />
  <!-- Page and Page Fragment Caches -->
<cachename="simplePageCache"
  maxEntriesLocalHeap="10"
  eternal="false"
  timeToIdleSeconds="10000"
  timeToLiveSeconds="10000"
  overflowToDisk="true">
</cache>
</ehcache>

Pros

  • No code is required.
  • It allows the content compressing.
  • This can be integrated with Spring WebFramework too.

Cons

  • It do caching based on complete response.
  • It doesn’t take custom headers in account.

Hibernate Caching

I found some useful information on internet about hibernate caching.I thought of sharing with everyone.
High-volume database traffic is a frequent cause of performance problems in Web applications. Hibernate is a high-performance, object/relational persistence and query service. In many cases, second-level caching can be just what Hibernate needs to realize its full performance-handling potential.

What is caching – Anything you can do to minimize traffic between a database and an application server is probably a good thing. In theory, an application ought to be able to maintain a cache containing data already loaded from the database, and only hit the database when information has to be updated. When the database is hit, the changes may invalidate the cache.

There are two different cache used in hibernate-
1. First Level cache – This is associated with session. This is default implemented in hibernate on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications
2. Second level cache – This is associated with Session Factory object. It will survive Sessions and can be reused in new Session by same SessionFactory (which usually is one per application). By default the 2nd level cache is not enabled. This ‘second-level’ cache exists as long as the session factory is alive. The second-level cache holds on to the ‘data’ for all properties and associations for individual entities that are marked to be cached. The second level cache is responsible for caching objects across sessions.

Cache Type
EHCache (Easy Hibernate Cache) — http://ehcache.sourceforge.net/
OSCache (Open Symphony) — http://www.opensymphony.com/oscache/
SwarmCache — http://swarmcache.sourceforge.net/
JBoss TreeCache — http://jboss.org/wiki/Wiki.jsp?page=JBossCache

EHCache -s an open source widely used java distributed cache for general purpose caching, Java EE and light-weight containers. It features memory and disk stores, replicate by copy and invalidate, listeners, cache loaders, cache extensions, cache exception handlers, a gzip caching servlet filter, RESTful and SOAP APIs and much more. Ehcache is available under an Apache open source license and is actively developed, maintained and supported.It support read only, Non strict Read/write,Read/write caching.It does not support transactional caching architecture.
OSCache – is “a Java framework” developed by OpenSymphony that makes it easy to cache content in Web applications.It is a caching solution that includes a JSP tag library and set of classes to perform fine grained dynamic caching of JSP content, servlet responses or arbitrary objects.It provides both in memory and persistent on disk caches.They can allow your site to have graceful error tolerance .It support read only, Non strict Read/write,Read/write caching.It does not support transactional schema caching architecture.
SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching. This type of cache is appropriate for applications that typically have many more read operations than write operations.It support read only, Non strict Read/write caching.It does not support ,Read/write and transactional caching architecture.It is is a cluster-based caching.
JBoss TreeCache – is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.

ref- http://www.devx.com/dbzone/Article/29685/1954
– http://javaexp.blogspot.com/2007/10/level2-caching-in-hibernate.html

pimp it