Tuesday

Ehcache hello world example

Ehcache is a Java open source cache implematation.

Download ehcache-2.9.0.jar and add to build path.

https://mvnrepository.com/artifact/net.sf.ehcache/ehcache/2.9.0 
For maven:
<dependency>

                <groupId>net.sf.ehcache</groupId>

                <artifactId>ehcache</artifactId>

                <version>2.9.0</version>

</dependency>
Download slf4j-api-1.6.1.jar (for Ehcache log) and add to build path.

https://mvnrepository.com/artifact/org.slf4j/slf4j-api/1.6.1

For maven:
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.1</version>
</dependency>
Download slf4j-jdk14-1.7.5.jar and add to build path.

https://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14/1.7.5

For maven:
 <dependency>

    <groupId>org.slf4j</groupId>

    <artifactId>slf4j-jdk14</artifactId>

    <version>1.7.5</version>

</dependency>

package main.java.com.code.more.talk.less;

import main.java.com.code.more.talk.less.cache.CacheExample;

public class Test {
      
       public static void main(String[] args) {
             
              CacheExample.getInstance().putElementToCache("months", "1", "Jan");
              CacheExample.getInstance().putElementToCache("months", "2", "Feb");
             
              System.out.println( CacheExample.getInstance().isKeyInCache("months", "1") );
              System.out.println( CacheExample.getInstance().isKeyInCache("months", "5") );
             
              System.out.println( CacheExample.getInstance().getValueofKeyFromCache("months", "1") );
              System.out.println( CacheExample.getInstance().getValueofKeyFromCache("months", "2") );
              System.out.println( CacheExample.getInstance().getValueofKeyFromCache("months", "5") );

       }

}

package main.java.com.code.more.talk.less.cache;

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

public class CacheExample {
               
                private static CacheManager cacheMgr = null;
                private static CacheExample ex = new CacheExample();
               
                public static  CacheExample getInstance() {
                                ex.initCacheManager();
                                return ex;
                }
               
                public Cache getCache(String cacheName) {
                                return cacheMgr.getCache(cacheName);
                }
               
                public void addCache(String cacheName) {
                                cacheMgr.addCache(cacheName);
                }
               
                public void putElementToCache(String cacheName, String key, String value) {
                                getCache(cacheName).put(new Element(key,value));
                }
               
                public boolean isKeyInCache(String cacheName, String key) {
                                return getCache(cacheName).isKeyInCache(key);
                }
               
                public String getValueofKeyFromCache(String cacheName, String key) {
                                Element ele = getCache(cacheName).get(key);
                                String value = (ele == null) ? null : (ele.getObjectValue().toString());
                                return value;
                }
               
                public void shutDown(){
                                cacheMgr.shutdown();
                }
               
                private void initCacheManager() {
                                if(cacheMgr == null) {
                                                synchronized(this) {
                                                                if(cacheMgr == null)
                                                                                cacheMgr = CacheManager.newInstance("src/main/resources/ehcache.xml");
                                                }
                                }

                }
               
                @Override
               public Object clone() throws CloneNotSupportedException {
                    throw new CloneNotSupportedException();
               }

}

Add ehcache.xml file to the following path: "src/main/resources/ehcache.xml"
<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, which in this configuration will go to wherever java.io.tmp is
    defined on your system. On a standard Linux system this will be /tmp" -->
       <cache name="months"
              maxEntriesLocalHeap="1000"
              maxEntriesLocalDisk="10000"
              eternal="false"
              diskSpoolBufferSizeMB="20"
              timeToIdleSeconds="300" timeToLiveSeconds="600"
              memoryStoreEvictionPolicy="LFU"
              transactionalMode="off">
              <persistence strategy="localTempSwap" />
       </cache>

</ehcache>

Output:
true
false
Jan
Feb
null

ehcache.xml configuration:
Expiration:
The maximum number of seconds an element can exist in the cache
whatever the access is. = timeToIdleSeconds  
without being accessed. = timeToLiveSeconds
The element expires at this limit and won't be returned from the cache. 
However eternal attribute overrides both of them if it is true so no expiration happens.

Memory Use:
If overflow is enabled, a check for expiry is carried out. 
The eviction of an item from the memory store: memoryStoreEvictionPolicy:
Least Recently Used (LRU) *Default**
Least Frequently Used (LFU)
Least Frequently Used (LFU)
Strategy Options: (<persistence strategy="" />)
localTempSwap: When the node is restarted, any existing data on disk is cleared because it is not designed to be reloaded.
localRestartable: After any restart, the data set is automatically reloaded from disk to the in-memory stores.
References for ehcache.xml configuration:  
http://www.ehcache.org/generated/2.9.0/pdf/Ehcache_Configuration_Guide.pdf

No comments:

Post a Comment