Sunday, June 26, 2011

Caching with ECache

download Ehcache (www.http://ehcache.org/) from website, unzip it and use ehcache.xml inside root folder

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

/**
 * The Class ClipBoard.
 *
 * @author Varra
 * @version 1.0
 */
public class ClipBoard
{
   
    /** The cache. */
    static Cache cache = null;
    static
    {
        CacheManager cacheManager = null;
        try
        {
            cacheManager = CacheManager
                    .create("C:/Users/varra/Desktop/MPPSources/MeiboPeoplePack/Packaging/Tools/Meibo/Studio/ehcache.xml");
        }
        catch (CacheException e)
        {
            e.printStackTrace();
        }
        cache = cacheManager.getCache("sampleCache1");
    }
   
    /**
     * The main method.
     *
     * @param args
     *            the arguments
     * @throws IllegalStateException
     *             the illegal state exception
     * @throws CacheException
     *             the cache exception
     */
    public static void main(String[] args) throws IllegalStateException, CacheException
    {
        String result = doit("a");
        System.out.println(result);
        result = doit("a");
        System.out.println(result);
    }
   
    /**
     * Doit.
     *
     * @param key
     *            the key
     * @return the string
     * @throws IllegalStateException
     *             the illegal state exception
     * @throws CacheException
     *             the cache exception
     */
    public static String doit(String key) throws IllegalStateException, CacheException
    {
        String result;
        // get an element from cache by key
        Element e = cache.get(key);
        if (e != null)
        {
            result = (String) e.getValue();
            System.out.println("retrieved " + result + " from cache ");
        }
        else
        {
            result = "new value";
            cache.put(new Element(key, result));
        }
        return result;
    }
}

No comments:

Post a Comment