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

戏子无情 提交于 2019-12-06 23:45:46

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3694861/how-to-configure-ehcache-for-standalone-java-program-without-using-hibernate-s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!