Common ehcache APIs

Source: Internet
Author: User

Cache technology has always been a high-level topic in applications, but today it posts an ehcache low-level backup. Refer to its official documents for sorting.
Ehcache API:

1: using the cachemanager

1.1 All ehcache usage starts from cachemanager.
There are multiple ways to create a cachemanager instance:

//Create a singleton CacheManager using defaults, then list caches.CacheManager.getInstance()

Or:
// Create a cachemanager instance Using defaults, then list caches.
Cachemanager manager = new cachemanager ();
String [] cachenames = manager. getcachenames ();

To create a cachemanager from a specified configuration file:
Create two cachemanagers, each with a different configuration, and list the caches in each.
Cachemanager manager1 = new cachemanager ("src/config/ehcache1.xml ");
Cachemanager manager2 = new cachemanager ("src/config/ehcache2.xml ");
String [] cachenamesformanager1 = manager1.getcachenames ();
String [] cachenamesformanager2 = manager2.getcachenames ();

1.2 adding and removing caches programmatically
Create a cache manually, instead of using the configuration file:
// Creates a cache called testcache, which
// Will be configured using defaultcache FROM THE CONFIGURATION
Cachemanager singletonmanager = cachemanager. Create ();
Singletonmanager. addcache ("testcache ");
Cache test = singletonmanager. getcache ("testcache ");

Or:
// Create a cache and add it to the cachemanager, then use it. Note that caches are not usable until they have
// Been added to a cachemanager.
Public void testcreatcachebyprogram ()
{
Cachemanager singletonmanager = cachemanager. Create ();
Cache memoryonlycache = new cache ("testcache", 5000, false, false, 5, 2 );
Singletonmanager. addcache (memoryonlycache );
Cache testcache = singletonmanager. getcache ("testcache ");
Assertnotnull (testcache );
}
 
Manually remove a cache:
// Remove cache called samplecache1
Cachemanager singletonmanager = cachemanager. Create ();
Singletonmanager. removecache ("samplecache1 ");

1.3 shutdown the cachemanager
Ehcache should be disabled after use. The best practice is to explicitly call the ehcache in the Code:
// Shutdown the singleton cachemanager
Cachemanager. getinstance (). Shutdown ();

 

2 using caches
For example, I have a cache:
<Cache name = "samplecache1" maxelementsinmemory = "10000"
Maxelementsondisk = "1000" Eternal = "false" overflowtodisk = "true"
Diskspoolbuffersizemb = "20" timetoidleseconds = "300"
Timetoliveseconds = "600" memorystoreevictionpolicy = "LFU"/>

2.1 obtaining a reference to a cache
Get the reference of this cache:
String cachename = "samplecache1 ";
Cachemanager manager = new cachemanager ("src/ehcache1.xml ");
Cache cache = manager. getcache (cachename );

2.2 faster Ming crud operations
The following code demonstrates the addition, deletion, modification, and query of ehcache:
Public void testcrud ()
{
String cachename = "samplecache1 ";
Cachemanager manager = new cachemanager ("src/ehcache1.xml ");
Cache cache = manager. getcache (cachename );
// Put an element into a cache
Element element = new element ("key1", "value1 ");
Cache. Put (element );
// This updates the entry for "key1"
Cache. Put (new element ("key1", "value2 "));
// Get a serializable value from an element in a cache with a key of "key1 ".
Element = cache. Get ("key1 ");
Serializable value = element. getvalue ();
// Get a nonserializable value from an element in a cache with a key of "key1 ".
Element = cache. Get ("key1 ");
Assertnotnull (element );
Object valueobj = element. getobjectvalue ();
Assertnotnull (valueobj );
// Remove an element from a cache with a key of "key1 ".
Assertnotnull (Cache. Get ("key1 "));
Cache. Remove ("key1 ");
Assertnull (Cache. Get ("key1 "));

}
 
2.3 disk persistence on demand
// Samplecache1 has a persistent diskstore. We wish to ensure that the data and index are written immediately.
Public void testdiskpersistence ()
{
String cachename = "samplecache1 ";
Cachemanager manager = new cachemanager ("src/ehcache1.xml ");
Cache cache = manager. getcache (cachename );
For (INT I = 0; I <50000; I ++)
{
Element element = new element ("key" + I, "myvalue" + I );
Cache. Put (element );
}
Cache. Flush ();
Log. debug ("Java. Io. tmpdir =" + system. getproperty ("Java. Io. tmpdir "));
}
Note: the path from persistent to hard disk is determined by the virtual machine parameter "Java. Io. tmpdir.
For example, in windows
C:/Documents and Settings/Li/Local Settings/temp
In Linux

2.4 obtaining cache sizes
The following code obtains the number of caches:
Public void testcachesizes ()
{
Long Count = 5;
String cachename = "samplecache1 ";
Cachemanager manager = new cachemanager ("src/ehcache1.xml ");
Cache cache = manager. getcache (cachename );
For (INT I = 0; I <count; I ++)
{
Element element = new element ("key" + I, "myvalue" + I );
Cache. Put (element );
}
// Get the number of elements currently in the cache.
Int elementsincache = cache. getsize ();
Asserttrue (elementsincache = 5 );
// Cache = manager. getcache ("samplecache1 ");
Long elementsinmemory = cache. getmemorystoresize ();
// Get the number of elements currently in the diskstore.
Long elementsindiskstore = cache. getdiskstoresize ();
Asserttrue (elementsinmemory + elementsindiskstore = count );
}
 
3: Registering cachestatistics in an mbeanserver
Ehcache supports JMX:
Cachemanager manager = new cachemanager ();
Mbeanserver = managementfactory. getplatformmbeanserver ();
Managementservice. registermbeans (Manager, mbeanserver, false, true );
Package the program and then:
Java-DCOM. Sun. Management. jmxremote-jar program name. Jar

Run jconsole.exe in javahome/binto monitor the cache.

4. You can customize cacheeventhandler to process various events such as events (events such as put, remove, and expiration) When an element is put into the cache)
Only three steps are required:
4.1 Add the cacheeventlistenerfactory node in the cache configuration.
<Cache name = "test" maxelementsinmemory = "1" Eternal = "false"
Overflowtodisk = "true" timetoidleseconds = "1" timetoliveseconds = "2"
Diskpersistent = "false" diskexpirythreadintervalseconds = "1"
Memorystoreevictionpolicy = "LFU">
<Cacheeventlistenerfactory class = "Co. ehcache. eventfactory"/>
</Cache>
4.2: Compile eventfactory to inherit cacheeventlistenerfactory:
Public class eventfactory extends cacheeventlistenerfactory
{
@ Override
Public cacheeventlistener createcacheeventlistener (properties Properties)
{
// Todo auto-generated method stub
Return new cacheevent ();
}

}

4.3 compile class: cacheevent to implement the cacheeventlistener interface:
Public class cacheevent implements cacheeventlistener
{

Public void dispose ()
{
Log ("in dispose ");
}

Public void notifyelementevicted (ehcache cache, element)
{
// Todo auto-generated method stub
Log ("in your yelementevicted" + element );
}

Public void notifyelementexpired (ehcache cache, element)
{
// Todo auto-generated method stub
Log ("in your yelementexpired" + element );
}

Public void notifyelementput (ehcache cache, element) throws cacheexception
{
// Todo auto-generated method stub
Log ("in your yelementput" + element );
}

Public void notifyelementremoved (ehcache cache, element) throws cacheexception
{
// Todo auto-generated method stub
Log ("in your yelementremoved" + element );
}

Public void notifyelementupdated (ehcache cache, element) throws cacheexception
{
// Todo auto-generated method stub
Log ("in your yelementupdated" + element );
}

Public void policyremoveall (ehcache cache)
{
// Todo auto-generated method stub
Log ("in policyremoveall ");
}
 
Public object clone () throws clonenotsupportedexception
{
Return super. Clone ();
}

Private void log (string S)
{
Log. debug (s );
}
}

Now you can write the test code:
Public void testeventlistener ()
{
String key = "person ";
Person = new person ("LCL", 100 );
Mycachemanager. getinstance (). Put ("test", key, person );
Person P = (person) mycachemanager. getinstance (). Get ("test", key );

Try
{
Thread. Sleep (10000 );
}
Catch (interruptedexception E)
{
// Todo auto-generated Catch Block
E. printstacktrace ();
}

Assertnull (mycachemanager. getinstance (). Get ("test", key ));
}
 
According to the configuration, the life cycle of the cached object is only 2 minutes. During thread. Sleep (10000), the cached element will expire and be destroyed. The notifyelementexpired event will be triggered before it is destroyed.
 
Ii. ehcache configuration file
The following configuration is used as an example:
 
<Cache name = "cache_func" maxelementsinmemory = "2" Eternal = "false" timetoidleseconds = "10" timetoliveseconds = "20"
Overflowtodisk = "true" diskpersistent = "true" diskexpirythreadintervalseconds = "120"/>
Maxelementsinmemory: the maximum number of elements that can be stored in the cache. If the element in the cache exceeds this value, there are two situations:
1. If the overflowtodisk attribute value is true, the extra elements in the cache will be put into the disk file.
2. If the overflowtodisk attribute value is false, the original elements in the cache will be replaced according to the memorystoreevictionpolicy.
Eternal: whether to stay in memory forever. If the value is true, the elements in the cache will remain in the memory and will not be lost due to time-out. Therefore, when the value is true,
The values of timetoidleseconds and timetoliveseconds do not work.
Timetoidleseconds: maximum interval between elements in the cache. If an element in the cache is not accessed after this time, it will be cleared from the cache.
Timetoliveseconds: The survival time of elements in the cache. It indicates the time from the time when an element in the cache is created to the time when it expires. When this time expires, the element is cleared from the cache.
Overflowtodisk: whether to overwrite data to the disk. According to the <diskstore Path = "Java. io. in tmpdir "/>, find the corresponding property value for the path value, if the system's Java. io. the value of tmpdir is D:/temp,
The files written to the disk are placed in this folder. The file name is the cache name, with the suffix data. For example, cache_func.data.
Diskexpirythreadintervalseconds: The interval between disk cache cleanup threads.
Memorystoreevictionpolicy: memory storage and release policy. There are three values:
LRU-least recently used
LFU-least frequently used
FIFO-first in first out, the oldest element by creation time
Diskpersistent: whether the disk cache is persistent. When the value of this attribute is true, the system will find the file in the disk with the name of the cache and the suffix "Index", such as cache_func.index, during initialization.
This file stores the index of the cache that has been persisted in the disk, and loads the cache to the memory. To make the cache truly persistent to the disk, you must pay attention to it when writing programs,
Use the void flush () method after using the void put (element) method of Net. SF. ehcache. cache.
For more information, see the description of ehcache. XML that comes with ehcache.

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.