EHCache Hello World Example

EHCache Hello World Example

This is a basic example to help you getting start with EHCache. Technologies used in this examples are

  • Ehcache 2.10.2
  • Maven
  • JDK 1.7

1. POM entry to include Ehcache in Maven project

<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache</artifactId>
	<version>2.10.2</version>
</dependency>

2. Folder structure of the project

Ehcache

3. Basic example of Ehcache

package com.code2succeed.ehcache;

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

public class EHCacheExample {
    public static void main(String[] args) {
        //1. Create cache manager
        CacheManager cm = CacheManager.getInstance();

        //2. Create a cache called "cache1"
        cm.addCache("cache1");

        //3. Get cache1
        Cache cache = cm.getCache("cache1");

        //4. Put few elements in cache
        cache.put(new Element(1, "Monday"));
        cache.put(new Element(2, "Tuesday"));
        cache.put(new Element(3, "Wednesday"));

        //5. Get all keys of cache 
        System.out.println("Keys in Cache: " + cache.getKeys());

        //6. Get 1st element from cache
        Element ele = cache.get(1);

        //7. Print out the element
        String output = (ele == null ? null : ele.getObjectValue().toString());
        System.out.println(output);

        //8. Is key in cache?
        System.out.println(cache.isKeyInCache(1));
        System.out.println(cache.isKeyInCache(5));

        //9. shut down the cache manager
        cm.shutdown();
    }
}

Output

Keys in Cache: [2, 1, 3]
Monday
true
false

We are done with Hello world application with EhCache. When we are not defining any property file for Ehcache then cache is created with default values. Cache in Ehcache is created with some basic properties which are listed below.

status = STATUS_ALIVE 
eternal = false 
overflowToDisk = true 
maxEntriesLocalHeap = 10000 
maxEntriesLocalDisk = 10000000 
memoryStoreEvictionPolicy = LRU 
timeToLiveSeconds = 120 
timeToIdleSeconds = 120 
persistence = LOCALTEMPSWAP 
diskExpiryThreadIntervalSeconds = 120 
cacheEventListeners: ; 
orderedCacheEventListeners:  
maxBytesLocalHeap = 0 
overflowToOffHeap = false 
maxBytesLocalOffHeap = 0
maxBytesLocalDisk = 0 
pinned = false

We can change these default values with the help of configuration file. Let us create an ehcache.xml and put it into the src/main/resources folder.

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
	monitoring="autodetect" dynamicConfig="true">

	<!-- By default, Ehcache stored the cached files in temp folder. -->
	<!-- <diskStore path="java.io.tmpdir" /> -->
	
	<!-- Ask Ehcache to store cache in this path -->
	<diskStore path="c:\\cache" />

	<!-- Sample cache named cache1
    This cache contains a maximum in memory of 10000 elements, and will expire
    an element if it is idle for more than 5 minutes and lives for more than
    10 minutes.

    If there are more than 10000 elements it will overflow to the
    disk cache -->
	<cache name="cache1" 
		maxEntriesLocalHeap="10000"
		maxEntriesLocalDisk="1000" 
		eternal="false" 
		diskSpoolBufferSizeMB="20"
		timeToIdleSeconds="300" timeToLiveSeconds="600"
		memoryStoreEvictionPolicy="LFU" 
		transactionalMode="off">
		<persistence strategy="localTempSwap" />
	</cache>
</ehcache>

TestClass to check configuration changes

package com.code2succeed.ehcache;

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

public class EHCacheExample {
    public static void main(String[] args) {
        //1. Create cache manager
        CacheManager cm = CacheManager.getInstance();

        //2. Create a cache called "cache1"
        cm.addCache("cache1");

        //3. Get cache1
        Cache cache = cm.getCache("cache1");

        //4. Put few elements in cache
        cache.put(new Element(1, "Monday"));
        cache.put(new Element(2, "Tuesday"));
        cache.put(new Element(3, "Wednesday"));

        //5. Get all keys of cache 
        System.out.println("Keys in Cache: " + cache.getKeys());

        //6. Get 1st element from cache
        Element ele = cache.get(1);

        //7. Print out the element
        String output = (ele == null ? null : ele.getObjectValue().toString());
        System.out.println(output);

        //8. Is key in cache?
        System.out.println(cache.isKeyInCache(1));
        System.out.println(cache.isKeyInCache(5));

        //9. Print cache configuration parameters
        System.out.println("Cache parameters : " + cache);

        //10. shut down the cache manager
        cm.shutdown();
    }
}

Output

Keys in Cache: [2, 1, 3]
Monday
true
false
Cache parameters : [ name = cache1 status = STATUS_ALIVE eternal = false overflowToDisk = true maxEntriesLocalHeap = 10000 maxEntriesLocalDisk = 1000 memoryStoreEvictionPolicy = LFU timeToLiveSeconds = 600 timeToIdleSeconds = 300 persistence = LOCALTEMPSWAP diskExpiryThreadIntervalSeconds = 120 cacheEventListeners: ; orderedCacheEventListeners:  maxBytesLocalHeap = 0 overflowToOffHeap = false maxBytesLocalOffHeap = 0 maxBytesLocalDisk = 0 pinned = false ]

As we can see, now the default parameters of cache is overridden by parameters from configuration file.

Leave a Reply

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