EhCache usage and principles

Source: Internet
Author: User

EhCache usage and principles

Introduction: EhCache is a Java-only in-process cache framework. It features fast and efficient, and is the default CacheProviderOSCache in Hibernate.

Applicable places:

 Features:

FIFO: first in first out.

LFU: Less Frequently Used, which has been Used at least for a long time will be cleared. The cached element has an hit attribute, and the smallest hit value will be cleared out of the cache.

LRU: Least Recently Used, which is Least Recently Used. The cached element has a timestamp. When the cache capacity is full and you need to make room for caching new elements, the elements whose timestamp is the farthest from the current time in the existing cache will be removed from the cache.

2. There are two levels of cache data storage locations: memory and disk, so there is no need to worry about capacity issues

3. the cached data will be written to the disk during the VM restart process.

Deep principles: Detailed explanation of http://raychase.iteye.com/blog/1545906
Related Configuration:

  1. Use your own Encoding

    Xml file Configuration:

<Ehcache> <! -- Specify a file directory. When EHCache writes data to the hard disk, it writes the data to the directory --> <diskStore path = "java. io. tmpdir"/> <! -- Set the default cache data expiration Policy --> <defaultCache maxElementsInMemory = "10000" eternal = "false" overflowToDisk = "true" timeToIdleSeconds = "0" timeToLiveSeconds = "0" diskPersistent =" false "diskExpiryThreadIntervalSeconds =" 120 "/> <cache name =" TESTCACHE "maxElementsInMemory =" 1000 "eternal =" true "overflowToDisk =" true "/> </ehcache>

 

Ehcache. xmlElement attributes:
Name: cache name

MaxElementsInMemory: Maximum number of cached objects in memory

MaxElementsOnDisk: Maximum number of cached objects in a hard disk. If it is 0, it indicates infinity.

Eternal: true indicates that the object never expires. The timeToIdleSeconds and timeToLiveSeconds attributes are ignored. The default value is false.

OverflowToDisk: true indicates that when the number of objects in the memory cache reaches the maxElementsInMemory limit, the overflow objects will be written to the hard disk cache. Note: If the cached object is to be written to the hard disk, the object must implement the Serializable interface.

DiskSpoolBufferSizeMB: disk cache size. The default value is 30 MB. Each Cache should have its own Cache zone.

DiskPersistent: Indicates whether to cache data during VM restart.

DiskExpiryThreadIntervalSeconds: Specifies the interval for running the disk invalidation thread. The default value is 120.

TimeToIdleSeconds: sets the maximum time allowed for idle objects, in seconds. After the last access, if the idle time of the object exceeds the timeToIdleSeconds attribute value, the object will expire and EHCache will clear it from the cache. Only when the eternal attribute is false

Valid. If the property value is 0, the object can be idle for an indefinite period of time.

TimeToLiveSeconds: sets the maximum time allowed for an object to exist in the cache, in seconds. After an object is stored in the cache, if the cache time exceeds the timeToLiveSeconds attribute value, the object will expire and EHCache will clear it from the cache. This attribute is available only when the eternal attribute is false.

Effect. If the value of this attribute is 0, it indicates that the object can exist in the cache indefinitely. TimeToLiveSeconds must be greater than the timeToIdleSeconds attribute.

MemoryStoreEvictionPolicy: When the maxElementsInMemory limit is reached, Ehcache clears the memory according to the specified policy. Optional policies include LRU (least recently used, default policy), FIFO (first-in-first-out), and LFU (minimum number of visits ).

  

Java programming code:

      

      

// Search for ehcache from the classes directory. xml configuration file CacheManager cacheManager = CacheManager. getInstance (); // query the configuration file with the specified name from the classes directory // CacheManager cacheManager = CacheManager. create (getClass (). getResource ("/ehcache. xml "); // obtain the Cache instance Cache = cacheManager Based on the configuration file. getCache ("TESTCACHE"); // clear all element Cache in the cache. removeAll (); // Add the element Cache to the cache. put (new Element ("s1", "11111"); cache. put (new Element ("s2", "22222"); cache. put (new Element ("s3", "33333"); // obtain the Element e = Cache from the cache. get ("s3"); System. out. println (e. getValue (); // uninstall the cache manager cacheManager. shutdown ();

     

  

2. Used as servlet Cache

  

Configuration in web. xml

      

        <filter>             <filter-name>SimplePageFragmentCachingFilter</filter-name>              <filter-class>                  net.sf.ehcache.constructs.web.filter.SimplePageFragmentCachingFilter              </filter-class>        </filter>        <filter-mapping>            <filter-name>SimplePageFragmentCachingFilter</filter-name>            <url-pattern>/*</url-pattern>        </filter-mapping> 

Configuration in ehcache. xml

    <?xml version="1.0" encoding="UTF-8"?>    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false"        monitoring="on">        <diskStore path="java.io.tmpdir" />        <defaultCache                 maxElementsInMemory="10000"                   eternal="false"                timeToIdleSeconds="3600"                 timeToLiveSeconds="3600"                 overflowToDisk="true"                diskPersistent="false"                diskExpiryThreadIntervalSeconds="3600"                 memoryStoreEvictionPolicy="LRU"/>                    <cache name="SimplePageFragmentCachingFilter"                maxElementsInMemory="10000"               maxElementsOnDisk="100000"                overflowToDisk="true"                diskSpoolBufferSizeMB="5120"               eternal="false"                timeToIdleSeconds="86400"                timeToLiveSeconds="0"               memoryStoreEvictionPolicy="LFU" />      </ehcache> 

In this case, you need to import the jar package: ehcache-web-2.0.4.jar

When used as a servlet cache, I intercept all request paths in the project. Some problems have occurred in the actual application. After updating the js, css, or jsp files in the project, the changes do not take effect immediately. Check the files on the server and find that the changes have been successful. So I guess it is caused by the Ehcache cache, so I cleared the cache.

File directory and tomcat working directory.

 

:Ehcache 2.5.1: http://sourceforge.net/projects/ehcache/files/ehcache/ehcache-2.5.1/


Ehcache alone is invalid.

Try CacheManager and Cache Singleton

What are the advantages and disadvantages of the cache engine Ehcache and OSCache used in Hibernate?

Ehcache is mainly used to cache database access. The same query statement only needs to be queried once, which improves the query speed.
Oscache is mainly used to cache pages. It can cache the whole page or a part of a webpage and specify its expiration time. In this way, the accessed data is the same during this period.

Hibernate2 previously advocated the use of ehcache
After hibernate3, we advocate oscache,

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.