Ehcache Cache Instance

Source: Internet
Author: User
Tags time interval

---restore content starts---

One: Catalog
    • EhCache Introduction
    • Hello World Example
    • Spring Integration
Two: Introduction 1. Basic introduction

EhCache is a pure Java in-process caching framework, which is fast and capable, and is the default Cacheprovider in Hibernate. Ehcache is a widely used, open source Java distributed cache. Primarily for general purpose caches, Java EE and lightweight containers. It features memory and disk storage, cache loaders, cache extensions, cache exception handlers, a gzip cache servlet filter, and support for rest and soap APIs.

Spring provides an abstraction of caching capabilities: that is, allowing different caching solutions to be bound (such as Ehcache), but does not natively provide the implementation of the caching functionality. It is very convenient to use the cache in annotation mode.

2. The main features are:
    1. Fast
    2. Simple
    3. Multiple cache policies
    4. Cache data has two levels: memory and disk, so there's no need to worry about capacity issues
    5. Cached data is written to disk during a virtual machine restart
    6. Distributed caching can be done via RMI, pluggable APIs, and more
    7. Listening interface with cache and cache manager
    8. Supports multi-cache manager instances, as well as multiple cache areas for one instance
    9. Provides a cache implementation of Hibernate
3. Integration

Can be used alone, generally in third-party libraries are used more (such as MyBatis, Shiro, etc.) Ehcache to the distributed support is not good enough, multiple nodes can not be synchronized, usually and redis a piece of use

4. Ehcache and Redis comparison
    • Ehcache is cached directly in the JVM virtual machine, fast and efficient, but the cache sharing is troublesome, the cluster distributed application is inconvenient.

    • Redis is accessed through the socket to the cache service, which is less efficient than ecache and much faster than a database.
      Processing clusters and distributed caches is convenient and has a proven solution. If it is a single application or a high-demand application for cache access, use Ehcache. Redis is recommended for large systems where cache sharing, distributed deployment, and cache content are large.

Ehcache also has a cache sharing scheme, but the broadcast cache notification update through RMI or Jgroup multicast, the cache sharing is complex, the maintenance is inconvenient; simple sharing is possible, but it involves cache recovery, big data caching is not appropriate.

Three: Hello World1, introducing dependency in Pom.xml
<dependency>    <groupId>net.sf.ehcache</groupId>    <artifactid>ehcache</ Artifactid>    <version>2.10.2</version></dependency>

2. Create a configuration file in src/main/resources/ehcache.xml

By default, Ehcache will automatically load the classpath root directory named Ehcache.xml file, or you can place the file somewhere else when you use it to specify the location of the file

<?xml version= "1.0" encoding= "UTF-8"?><ehcache> <!--represents the location where the cache is saved on the hard disk. The default is a temporary folder. -<!--<diskstore path= "Java.io.tmpdir"/>--> <diskstore path= "/logs/ehcache"/> <!--The default cache configuration, if the class does not have a specific setting, uses the cache properties configured here. Maxelementsinmemory-sets the maximum number of objects (POJO) that are allowed to be saved in the cache eternal-sets whether the object is persisted, and if true, the data in the cache is never destroyed and kept. Timetoidleseconds-set the idle destroy time. Only works if Eternal is false. Indicates that the cached data is destroyed if it exceeds this value from now to last access time Timetoliveseconds-set the active destroy time. Indicates that from now to cache creation time if this value is exceeded, the cache is automatically destroyed Overflowtodisk-Sets whether the excess portion is saved to the hard disk when the saved quantity is exceeded. -<Defaultcache maxelementsinmemory= "1500"Eternal= "false"Timetoidleseconds= "120"Timetoliveseconds= "300"Overflowtodisk= "true"/> <cache name= "Democache"maxelementsinmemory= "1000"Eternal= "true"Timetoidleseconds= "0"Timetoliveseconds= "0"Overflowtodisk= "true"/></ehcache>
3. Test class
 Public classMyehcache { Public Static voidMain (string[] args) {User User=NewUser ("Cache", "123456", "Cache Cache", "", "male", 20); //Get Cache ManagerCacheManager manager = cachemanager.create ("Src/main/resources/config/ehcache.xml"); //to obtain a cache instance from a configuration fileCache demo = Manager.getcache ("Democache"); //empty all elements in the cacheDemo.removeall (); Demo.put (NewElement ("Hello", "World")); Demo.put (NewElement (User.getusername (), user)); Element e=Demo.get (User.getusername ()); System.out.println (Demo.get ("Hello"). Getobjectvalue ());         System.out.println ((User) E.getobjectvalue ()). Getuserrealname ()); //uninstalling the Cache manager//Manager.shutdown ();    }}
4. Cache Configuration One: XML configuration method:
  • Diskstore:ehcache supports both memory and disk storage

    • Path: Specify the location of the disk storage
  • Defaultcache: Default Cache

    • Maxentrieslocalheap= "10000"
    • Eternal= "false"
    • Timetoidleseconds= "120"
    • Timetoliveseconds= "120"
    • maxentrieslocaldisk= "10000000"
    • Diskexpirythreadintervalseconds= "120"
    • Memorystoreevictionpolicy= "LRU"
  • Cache: Custom caching that can be customized (can contain multiple cache nodes) when the custom configuration does not meet the actual situation

    • Name: Names of the caches that can be obtained by specifying a name for a specified cache object

    • Maxelementsinmemory: The maximum number of elements allowed to be stored in memory, 0 for unlimited

    • Clearonflush: If the maximum amount of memory is cleared.

    • Eternal: Sets whether the object in the cache is permanent, and if so, the timeout setting is ignored and the object never expires. Depending on the data stored, such as static and unchanging data such as provinces and cities can be set to never obsolete

    • Timetoidleseconds: Sets the allowable idle time (in seconds) for an object before it expires. An optional property is used only if the Eternal=false object is not permanently valid, and the default value is 0, which means that the idle time is infinite.

    • Timetoliveseconds: The time-to-live (TTL) of the cached data, which is the maximum time 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.

    • Maxentrieslocaldisk: When the number of objects in memory reaches Maxelementsinmemory, Ehcache writes the object to disk.

    • Maxelementsondisk: Maximum number of hard disk caches.

    • DISKSPOOLBUFFERSIZEMB: This parameter sets the buffer size of the Diskstore (disk cache). The default is 30MB. Each cache should have its own buffer.

    • Diskpersistent: Whether to store the hard disk's cached data when the VM restarts. The default value is False.

    • Diskexpirythreadintervalseconds: Disk failed thread run time interval, default is 120 seconds.

Two: Programming mode configuration
Cache cache = Manager.getcache ("Mycache"= cache.getcacheconfiguration (); Config.settimetoidleseconds ( ); Config.settimetoliveseconds (+); Config.setmaxentrieslocalheap (10000); Config.setmaxentrieslocaldisk (1000000);
5. Ehcache API
    • Cachemanager:cache the Container object and manages (add or remove) the cache life cycle.
// You can create a cache object yourself to add to the CacheManager  Public void Addcache (cache cache);  Public synchronized void RemoveCache (String cachename);

    • Cache: A cache can contain multiple element and is managed by CacheManager. It implements the logical behavior of the cache

    • Element: The elements that need to be cached, which maintain a key-value pair, the element can also set the validity period, 0 means unlimited

    • How to get CacheManager:

      You can create a way to get cachemanager by using the Create () or newinstance () method or overloaded method:

 Public Static CacheManager Create ();  Public Static CacheManager Create (String configurationfilename);  Public Static CacheManager Create (InputStream inputstream);  Public Static CacheManager Create (URL configurationfileurl);  Public Static CacheManager newinstance ();

When a Ehcache CacheManager constructor or factory method is called, a configuration file named Ehcache.xml classpath is loaded by default.
If the load fails, the Ehcache-failsafe.xml file in the Ehcache jar package is loaded, and the file contains a simple default configuration.

 //  cachemanager.create () = = Cachemanager.create ("./src/main/resources/ehcache.xml")  //  Create a new CacheManager instance with ehcache default configuration  cachemanager cachemanager = Cachemanager.create (); CacheManager  = Cachemanager.newinstance (); CacheManager  = Cachemanager.newinstance ("./src/main/resources/ehcache.xml"  = new  fileinputstream (new  File ("./src/main/resources/ehcache.xml"  = cachemanager.newinstance (InputStream);  string[] Cachenames  = Cachemanager.getcachenames (); //  [Helloworldcache]  

Four: Spring integration 1, configuration Spring-ehcache.xml
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:cache= "Http://www.springframework.org/schema/cache"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp//Www.springframework.org/schema/cachehttp//www.springframework.org/schema/cache/spring-cache-3.2.xsd "><description>ehcache Cache Configuration Management file </description> <!--enable cache annotation Switch--<cache:annotation-driven cache-manager= "CacheManager"/> <bean id= "CacheManager"class= "Org.springframework.cache.ehcache.EhCacheCacheManager" > <property name= "CacheManager" ref= "Ehcache"/> </bean> <bean id= "Ehcache"class= "Org.springframework.cache.ehcache.EhCacheManagerFactoryBean" > <property name= "configlocation" value= " Classpath:ehcache.xml "/> </bean></beans>

---restore content ends---

Ehcache Cache Instance

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.