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)
First, put
net.sf.ehcache:ehcache:2.9.0
and its dependencies in your ClassPathTo 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.
- 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
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.
精彩评论