Ehcache cache data

1.ehcahe Profile

EhCache is a pure Java caching framework of the process, with fast, lean, etc., Hibernate is the default CacheProvider.

See the official website has been 3.0.

2. Role

I think of it as a data store and read data exists. Cache fact, a key-value data storage tool. Currently I have used two ways.

First, the data cache database.

It said the cost of connection to the database is large, so the data can change a small portion of the cached, the next to take data directly from the cache. (Security on data not considered).

The second is to store a variable.

In the back-end web development process, some data needs to be saved for next use. For example, SMS verification code. I always add a map before class class variable, then stored map, next time out or destroyed. Such things can, and after the class is instantiated. Class variable is loaded into memory, and can store data. But there is a question about the lifecycle of creating and destroying a class issue. What can not be sure that when he went to destroy. Or, I know this one is limited, not to study.

So, into the cache it. The size of the data cache may be provided time to failure.

3. Simple to use

(1 Overview

Ehcache is a pure Java caching framework of the process, with fast 'lean and so on.

Based on the above 2.10.X

 

(2) add the relevant packets in dependence pom.xml

 

<!--  ehcache缓存包-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

<-! Spring-context-support with respect to the cache function abstract Spring package interface -> 
<dependency>
<the groupId> org.springframework </ the groupId>
<the artifactId> context-Support-Spring </ the artifactId>
</ dependency >

(. 3) the helloWorld instance Ehcache buffer

1. Add ehcache.xml profile in classpath, add a buffer called the helloworld
---------------------- -------------------------------------------------- --------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>

<!-- 默认缓存 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>

<!-- helloworld缓存 -->
<cache name="helloworld"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>

</ehcache>
-------------------------------------------------------------------------------------------------------

<-! <DefaultCache
maxElementsInMemory = "10000" Maximum-memory cache object
eternal = "false" Element whether permanent, but a set, timeout will not work
timeToIdleSeconds = "120" disposed object allows idle before failure time (unit: seconds). Eternal = false only if the object is not a permanent use, optional attributes, the default value is 0, that is, the idle time may be infinity.
timeToLiveSeconds = "120" set object allows survival time before failure (unit: seconds). The maximum time between failure time and time of creation. Only when eternal = false object is not a permanent use, the default is 0.5, which is subject survival time infinity.
overflowToDisk = "true" is set when the in-memory cache to achieve maxInMemory restriction element whether on disk writes
maxElementsOnDisk = "10000000" default disk cache size is not limited, but can be specified by maxElementsOnDisk. When the disk cache reaches the specified value maxElementsOnDisk, Ehcache will clear the cache disk use the default strategy is LFU (the lowest frequency of use).
diskPersistent = "false" if the VM restart when persistent disk cache, the default is false.
diskExpiryThreadIntervalSeconds = "120" disk cache cleanup thread run interval, the default is 120 seconds.
memoryStoreEvictionPolicy = "LRU" when the memory cache is maximized when there is a new element added to remove the cache element of the strategy. The default is LRU, LFU and FIFO are optionally configurable as listeners and to the cache loader element.
/> ->

<-! <Cache
name = "SampleCache" Cache uniquely identifies
maxElementsInMemory = "5" Maximum memory cache object
maxElementsOnDisk = "100" default disk cache size is not limited, but can be specified by maxElementsOnDisk . When the disk cache reaches the specified value maxElementsOnDisk, Ehcache will clear the cache disk use the default strategy is LFU (the lowest frequency of use).
eternal = "false" Element whether permanent, but a set, timeout will not work
timeToIdleSeconds = "2" is provided to allow the object in idle time before failure (unit: seconds). Eternal = false only if the object is not a permanent use, optional attributes, the default value is 0, that is, the idle time may be infinity.
timeToLiveSeconds = "2" set object allows survival time before failure (unit: seconds). The maximum time between failure time and time of creation. Only when eternal = false object is not a permanent use, the default is 0.5, which is subject survival time infinity.
overflowToDisk = "true" when the set memory cache reaches maxInMemory restriction element may be written to disk if
/>

ehcache.xml configuration parameters:

  • name : the name of the cache.
  • maxElementsInMemory : the maximum number of cache.
  • Eternal : cache object is a permanent, if so, the timeout setting is ignored, the object never expires.
  • timeToIdleSeconds : placing object allowed idle time before failure (unit: seconds). Eternal = false only if the object is not a permanent use, optional attributes, the default value is 0, that is, the idle time may be infinity.
  • timeToLiveSeconds : time to live the cached data (TTL), which is an element of value from the maximum time interval to the demise of the building, which can only be effective when the element is not a permanent resident, if the value is 0 means that elements can be infinitely long pause time.
  • maxEntriesLocalDisk : when the number of objects in memory reaches maxElementsInMemory, Ehcache will target written to disk.
  • overflowToDisk : low memory, disk cache is enabled.
  • diskSpoolBufferSizeMB : This parameter sets the size of the buffer DiskStore (disk cache) of. The default is 30MB. Each Cache should have a buffer of its own.
  • maxElementsOnDisk : The maximum number of hard disk cache.
  • diskPersistent : cache data stored in the hard disk of whether to restart the VM. The default value is false.
  • diskExpiryThreadIntervalSeconds : disk fails thread run intervals, the default is 120 seconds.
  • memoryStoreEvictionPolicy : When reached maxElementsInMemory limit, Ehcache will go to clean up the memory according to the specified policy. The default policy is LRU (least recently used). You can set FIFO (First In First Out) or LFU (rarely used).
  • clearOnFlush : whether to remove the maximum amount of memory.


-------------------------------------------------- -------------------------------------------------- ---

2.EhcacheDemo.java file
Ehcache will automatically load the root directory of the classpath named ehcache.xml file.
EhcacheDemo work as follows:
In EhcacheDemo, we quote ehcache.xml called statement of helloworld cache to create Cachean object;
then we use a key-value pair to instantiate Elementan object;
to Elementadd objects to Cache;
then use the Cacheget method of obtaining Elementobjects .
-------------------------------------------------- --------------------------------------
package com.agesun.attendance.web.controller;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class EhcacheDemo {

public static void main(String[] args){
       // Create a cache manager to create a cache manager 
Final CacheManager CacheManager = new new CacheManager ();
// Called the Create at The Cache "helloworld" stated references ehcache.xml named helloworld create a cache Cache object
final Cache cache = cacheManager.getCache ( "the HelloWorld");
// the Create A Key to the Map to the Data at The
Final Key String = "the Greeting";
// the Create the Data Element A
Final Element putGreeting = new new Element (Key, "the Hello, World!");
// of Put the element into the data store // the object into the cache map cache
cache.put (putGreeting);
// // Retrieve the Data element obtained from a subject to cache elements
Final = cache.get the getGreeting the element (Key);
/ / Retrieve the data element
System.out.println(getGreeting.getObjectValue());
    }

}
-------------------------------------------------- -------------------------------- 

output:


(4) Ehcache basic operations

Element, Cache, cacheManager is Ehcacle most important API

Element: cache elements, maintains a key-value pair
Cache: Ehcache is the core classes, he has more Element, and CacheManager management, which implements the logical behavior of the cache
CacheManager: container object cache and cache manages the life cycle.


4.ehcache basic principles

ehcache is using a Java simple realization of use, speed, cache management to achieve thread-safe libraries, ehcache provided with a memory, disk files are stored , and distributed a variety of flexible cache management program storage methods. Meanwhile ehcache as an open source program , using more relaxed limit Apache License V2.0 as an authorized manner, it is widely used in Hibernate, Spring, Cocoon and other open systems .

Ehcache class hierarchy for the three main models, the uppermost layer is CacheManager , he is the entrance of Ehcache operation. We can get through a single CacheManager.getInstance () CacheManager, or create a new CacheManager by the constructor of CacheManager. Each CacheManager manages a multiple Cache. And each are in a class Cache Hash manner associated with a plurality of Elemenat. The Element is the place where we used to store the contents of the cache.

ehcache refresh refresh policy strategy ehcache that when a cache placed into the record time, it is Lazy Evict way, set at the same time taking the TTL Comparators

ehcache empty cache policy three kinds:. 1 the FIFO , FIFO 2 the LFU , the least used, the element has a cache hit attribute, the cache hit value will be cleared minimal. 3 the LRU , the least recently used cache element has a time stamp, when the cache capacity is full, but need to make room for the new element when the cache, then the existing cache elements from the current time timestamp farthest cache element will be cleared.

Event processing can add event listeners to CacheManager, when the additions and deletions to CacheManager Cache, the event handler will be notified. To configure the event handling, it needs to be done by ehcache profile. You can add an event listener for the Cache, Cache when to add or delete Element, the event handler will be notified. To configure the event handling, it needs to be done by ehcache profile.

Guess you like

Origin www.cnblogs.com/tongcc/p/11269339.html