开发者

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

开发者 https://www.devze.com 2023-01-16 00:54 出处:网络
Can anyone please post an example to configure Ehc开发者_如何学Cache for a standalone java application?

Can anyone please post an example to configure Ehc开发者_如何学Cache 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?


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.


Check the Code Samples and Recipes chapter for more information on direct interaction with ehcache.

Recipes and Code Samples

The Recipes and Code Samples page contains recipes - short concise examples for specific use cases - and a set of code samples that will help you get started with Ehcache.

They cover several use cases and provide several code samples, which is just what you're asking for.

0

精彩评论

暂无评论...
验证码 换一张
取 消