Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure EHcache for standalone Java program without using hibernate / spring interceptors?

Tags:

java

ehcache

Can anyone please post an example to configure Ehcache for a standalone java application?

I have the following simple requiremens:

  • getting data from database,
  • formatting that data and
  • writing to file

I am using jdbctemplate.Query, it is executing quickly but the retrieval from list is taking quite a while. List is holding large volume of data (resultset).

Can anyone suggest how to overcome this problem?

like image 608
ari Avatar asked Sep 12 '10 12:09

ari


1 Answers

This is a very old post, but it seems to kick back regularly so....

You should follow Pascal's advice and read those samples, but here is a snip of sample code to get you started (translated from Scala, I did not fully check the syntax)

  1. First, put net.sf.ehcache:ehcache:2.9.0 and its dependencies in your ClassPath

  2. To create a cache, it is as simple as

    CacheManager cacheMgr = CacheManager.newInstance();
    
    //Initialise a cache if it does not already exist
    if (cacheMgr.getCache("MyCache") == null) {
        cacheMgr.addCache("MyCache");
    }
    

Instantiate the CacheManager only once in your code and reuse it.

  1. The behaviour of your cache is dictated by an XML configuration file called ehcache.xml which must be available on your classpath. You can also do it programatically. The file could look like
    <ehcache>
        <diskStore path="java.io.tmpdir"/>
        <cache name="MyCache"
           maxEntriesLocalHeap="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxEntriesLocalDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU"
            >
           <persistence strategy="localTempSwap"/>
        </cache>
    </ehcache>

For details on the parameters, check http://ehcache.org/documentation/2.8/configuration/configuration

  1. Use it

    //use it
    Cache cache = cacheMgr.getCache("MyCache");
    
    //Store an element
    cache.put(new Element("key", mySerializableObj));
    
    //Retrieve an element
    Element el = cache.get("key");
    Serializable myObj = <Serializable>el.getObjectValue();
    

Try storing serializable objects so you can easily overflow to a storage device.

like image 158
Bruno Grieder Avatar answered Sep 19 '22 16:09

Bruno Grieder