A: Detailed configuration steps
1. Add Ehcache.xml File
Add the Ehcache.xml file to the SRC path. Ehcache.xml file contents are as follows
[HTML]View Plaincopyprint?
- <ehcache>
- <diskstore path="Java.io.tempdir" />
- <defaultcache maxelementsinmemory="$" eternal="false"
- timetoidleseconds="timetoliveseconds=" overflowtodisk= " true" />
- <cache name="Ehcachename" maxelementsinmemory="10000 "
- eternal="false" timetoidleseconds="300000" timetoliveseconds="600000"
- overflowtodisk="true" />
- </ehcache>
2. Add Spring configuration file
Add in the Appliccontext.xml file
[HTML]View Plaincopyprint?
- <Bean id="cachemanagerfactory"
- class="Org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
- p:configlocation="Classpath:ehcache.xml"></beans>
- <!--statement CacheManager--
- <Bean id="CacheManager" class= "Org.springframework.cache.ehcache.EhCacheCacheManager "
- p:cachemanager-ref="Cachemanagerfactory" ></beans>
Two: Use
1, defining the Ehcache tool method
[Java]View Plaincopyprint?
- Public class EHCache {
- private static final CacheManager CacheManager = new CacheManager ();
- private cache cache;
- Public Ehcacheservice () {
- This.cache=cachemanager.getcache ("Ehcachename")
- }
- Public Cache GetCache () {
- return cache;
- }
- public void Setcache (cache cache) {
- This.cache = cache;
- }
- /*
- * Get data from the cache by name
- */
- Public Object getcacheelement (String CacheKey) throws Exception {
- Net.sf.ehcache.Element e = Cache.get (CacheKey);
- if (e = = null) {
- return null;
- }
- return E.getvalue ();
- }
- /*
- * Add an object to the cache
- */
- public void Addtocache (String cacheKey, Object result) throws Exception {
- Element element = new Element (CacheKey, result);
- Cache.put (Element);
- }
- }
2, test
[Java]View Plaincopyprint?
- Public class test{
- EHCache EHCache = new EHCache ();
- public void Test () {
- //test storing JSON objects in cache
- Jsonobject obj = new Jsonobject ();
- Obj.put ("name","LSZ");
- Ehcache.addtocache ("Cache_json", obj);
- //Get from the cache
- Jsonobject getobj = (jsonobject) ehcache.getcacheelement ("Cache_json");
- System.out.println (Getobj.tostring ());
- }
- }
Three: Problem solving
1, the framework environment is self-built, add Ehcache after the run error:
Org.springframework.beans.factory.parsing.BeanDefinitionParsingException:Configuration problem:unable to locate Spring Namespacehandler for XML schema namespace [Http://www.springframework.org/schema/cache]
Offending Resource:class path resource [Applicationcontext.xml]
This problem occurs because in the Applicationcontext.xml file, you add more
<cache:annotation-driven cache-manager= "CacheManager"/> Remove it
2, the framework needs to add a jar package
Spring-context-support-3.2.0.release.jar
Spring-context-3.2.0.release.jar
Source: http://blog.csdn.net/lishuangzhe7047/article/details/41680921
Ehcache Cache Usage