Ehcache using Notes

Source: Internet
Author: User

To use Java's local cache, consider using Ehcache, or guava.

Guava more high-end, can be automatically timed refresh. I have chosen Ehcache.

The Ehcache is integrated in spring. To use Ehcache, you need only the following steps:

Of course, you need to first introduce Ehcache-related jar packages. You can use MAVEN dependencies to configure the Pom file.

First, configure the Ehcache related Bean in spring's applicationcontext.xml configuration file

    <!--Ehcache--    class= "Org.springframework.cache.ehcache.EhCacheManagerFactoryBean" >          <property name= "configlocation" value= "Spring/ehcache.xml"/>      </bean>      class= " Org.springframework.cache.ehcache.EhCacheCacheManager ">          <property name=" CacheManager "ref=" Cachemanagerfactory "/>    </bean>

Second, the configuration good ehcache.xml

<?XML version= "1.0" encoding= "GBK"?><EhcacheXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:nonamespaceschemalocation= "Ehcache.xsd">    <DiskstorePath= "Java.io.tmpdir"/>     <Defaultcachemaxelementsinmemory= "10000"Eternal= "false"Timetoidleseconds= "+"Timetoliveseconds= "+"Overflowtodisk= "false"/>    <!--Configure custom Cache maxelementsinmemory: The maximum number of objects that are allowed to be created in the cache eternal: whether the object in the cache is permanent, and if so, the timeout setting is ignored and the object never expires. Timetoidleseconds: The passivation time of the cached data, that is, the maximum time interval value of two access times before an element dies, which can only be valid if the element is not permanently resident, if the value is 0        The flavor element can pause for an infinite amount of time.        Timetoliveseconds: The lifetime of the cached data, that is, the maximum interval value of an element from build to extinction, which can only be valid if the element is not permanently resident, and if the value is 0 means that the element can pause for an infinite amount of time.        Overflowtodisk: If the disk cache is enabled when there is not enough memory.    Memorystoreevictionpolicy: Cache is full after the elimination algorithm.  -    <Cachename= "Territorycache"maxelementsinmemory= "10000"Eternal= "false"Overflowtodisk= "false"Timetoidleseconds= "The "Timetoliveseconds= "1800"Memorystoreevictionpolicy= "LFU" /> </Ehcache>

Third, the use of CacheManager in specific classes

@Component  Public class Territoryrangecache {    @Autowired    Ehcachecachemanager Manager;    @Autowired    Territoryrangedao Territoryrangedao;    Cache cache;      Public Object getallterritorranges (String key) {

cache = Manager.getcachemanager (). GetCache ("Territorycache");

        = Cache.get (key);         if NULL {            cache.putifabsent,new  Element (Key, Territoryrangedao.selectall ()             )); return Cache.get (key). Getobjectvalue ();        }         return Cache.get (key). Getobjectkey ();    } }

In fact, the use of injected Ehcachecachemanager in specific classes is spring's own encapsulated CacheManager. To get the CacheManager in the EhCache package, you need to take the spring wrapped Ehcachecachemanager through the getmanager. Let's look at the source of Ehcachecachemanager first:

 Public classEhcachecachemanagerextendsAbstracttransactionsupportingcachemanager {Private Net.sf.ehcache.CacheManager CacheManager; /*** Create A new Ehcachecachemanager, setting the target EhCache CacheManager * through the {@link#setCacheManager} Bean property. */     PublicEhcachecachemanager () {}/*** Create A new Ehcachecachemanager for the given backing EhCache CacheManager. * @paramCacheManager the backing EhCache {@linkNet.sf.ehcache.CacheManager}*/     PublicEhcachecachemanager (Net.sf.ehcache.CacheManager cachemanager) { This. CacheManager =CacheManager; }    /*** Set the backing EhCache {@linkNet.sf.ehcache.CacheManager}.*/     Public voidSetcachemanager (Net.sf.ehcache.CacheManager cachemanager) { This. CacheManager =CacheManager; }    /*** Return the backing EhCache {@linkNet.sf.ehcache.CacheManager}.*/     PublicNet.sf.ehcache.CacheManager Getcachemanager() {return  This. CacheManager; } ...}

Four, Ehcaceh the timing refresh, you can write a method to update the data in the cache:

@Scheduled (cron = "")    @PostConstruct    publicvoid  Refreshall () {        = Manager.getcachemanager (). GetCache ("key");        Getallterritorranges ("Territory_range");     }

You can add the method above to periodically flush the data in the cache using the parameters passed in the cron expression.

About the use of @postconstruct and meaning, will be in my other article blog post Introduction ~. You can first look at the source of this note:

 Packagejavax.annotation;Importjava.lang.annotation.*;Import StaticJava.lang.annotation.elementtype.*;Import StaticJava.lang.annotation.retentionpolicy.*;/** * The postconstruct annotation is used on a method, needs to being executed * after dependency injection is do to perf ORM any initialization. This * method must was invoked before the class is put into service. This * annotation must is supported on all classes the support dependency * injection.  The method annotated with Postconstruct must is invoked even * if the class does not a request any resources to be injected. Only one * method can is annotated with this annotation. The method on which the * postconstruct annotation are applied must fulfill all of the following * criteria-the method M  UST not all parameters except in the case of EJB * interceptors in which case it takes an invocationc Ontext object As * defined by the EJB specification. *-The return type of the method must be void. *-The method must not throw a checked exception. *-the method on which postconstruct are applied may are public, protected, * package private or private. *-the method must not being STatic except for the application client. *-the method may be final. *-If The method throws an unchecked exception the class must not being put into * service except in the case of EJBs where The EJB can handle exceptions and * even recover from them.  *@sinceCommon Annotations 1.0 *@seeJavax.annotation.PreDestroy *@seeJavax.annotation.Resource*/@Documented @retention (RUNTIME) @Target (METHOD) Public@Interfacepostconstruct {}

Read the notes and you can read them.

Ehcache using Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.