Installation
Ehcache
If your project uses MAVEN management, add the following dependencies to your pom.xml .
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.2</version> <type>pom</type></dependency>
If your project does not use MAVEN management, please download
Spring
If your project uses MAVEN management, add the following dependencies to your pom.xml .
spring-context-support
This jar package contains spring's abstract encapsulation interface for caching functionality.
<dependency> <groupId>org.springframework</groupId> <artifactid>spring-context-support </artifactId> <version>4.1.4.RELEASE</version></dependency>
Back to Top
Examples of using HelloWorld for Ehcache
The quickest and most direct way to touch a technology is always a Hello world example, after all, hands-on practice is more impressive, isn't it?
(1) Add ehcache.xml under Classpath
Add a cache named HelloWorld . Download
<?xml version= "1.0" encoding= "UTF-8"? ><ehcache xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance " xsi:nonamespaceschemalocation=" http:/ /ehcache.org/ehcache.xsd "> <!-- Disk cache location --> <diskstore path=" Java.io.tmpdir/ehcache "/> <!-- Default cache --> <defaultCache maxentrieslocalheap= "10000" eternal= "false" timetoidleseconds= " timetoliveseconds=" 120 " maxentrieslocaldisk= "10000000" diskexpirythreadintervalseconds= " " memoRystoreevictionpolicy= "LRU"/> <!-- helloworld Cache --> <cache Name= "HelloWorld" maxelementsinmemory= " " eternal= "false" timetoidleseconds= "5" timetoliveseconds= "5" overflowtodisk= "false" memorystoreevictionpolicy= "LRU"/></ehcache>
(2)Ehcachedemo.java
Ehcache will automatically load the classpath root directory namedEhcache.xmlFile.
Ehcachedemo's work steps are as follows:
In Ehcachedemo, we quoteEhcache.xmlThe declaration is namedHelloWorldCache to create theCache
Object
Then we instantiate it with a key-value pair.Element
Object
WillElement
object is added to theCache
;
and then useCache
The Get method getsElement
Object.
Public class ehcachedemo { public static void main (String [] args] throws exception { // create a cache manager final CacheManager Cachemanager = new cachemanager (); // create the cache called "HelloWorld" final cache cache = cachemanager.getcache ("HelloWorld"); // create a key to map the data to final String key = "Greeting"; // create a data element final element putgReeting = new element (key, "hello, world!"); // put the element into the data store cache.put (putgreeting); // Retrieve the data element final element getgreeting = cache.get (Key); // Print the value System.out.println (Getgreeting.getobjectvalue ()); }}
Output
Hello, world!.
Ehcache Basic Operation Download
Element
, Cache
and CacheManager
is the most important API for Ehcache.
Element: The elements of the cache, which maintain a key-value pair.
-
Cache: It is the core class of Ehcache, it has multiple element
, and was cachemanager
Management. It implements the logical behavior of the cache.
CacheManager: Cache
The Container object, and manages Cache
the life cycle.
Create CacheManagerThe following code lists the creationCacheManager
In five ways.
Using static methodscreate()
A singleton is created with the default configuration.CacheManager
Instance.
newInstance()
Method is a factory method that creates a new one with the default configurationCacheManager
Instance.
In additionnewInstance()
There are also several overloaded functions that can be passed through theString
、URL
、InputStream
parameter to load the configuration file, and then createCacheManager
Instance. Download
Use the Ehcache default configuration to obtain a singleton CacheManager instance cachemanager.create (); String[] cachenames = cachemanager.getinstance (). Getcachenames ();// Create a new CacheManager instance using the Ehcache default configuration cachemanager.newinstance (); String[] cachenames = manager.getcachenames ();// creates a CacheManager instance using a different configuration file CacheManager manager1 = cachemanager.newinstance ("Src/config/ehcache1.xml"); Cachemanager manager2 = cachemanager.newinstance ("Src/config/ehcache2.xml"); String[] cachenamesformanager1 = manager1.getcachenames (); String[] cachenamesformanager2 = manager2.getcachenames ();// Create CacheManager instance Url url = getclass () based on the configuration file under Classpath. GetResource ("/ Anotherconfigurationname.xml "); Cachemanager manager = cachemanager.newinstance (URL);// based on the file stream to get the configuration file, and create a CacheManager instance Inputstream fis = new fileinputstream (New file ("src/config/ Ehcache.xml "). GetAbsolutePath ()); Try { cachemAnager manager = cachemanager.newinstance (FIS);} finally { fis.close ();}
Add cache
It is important to emphasize that Cache
addCache
an object CacheManager
is not valid until it is added to the method.
The Addcache method of using CacheManager can be added to the container according to the cache name declared in Ehcache.xml, and it can also add the cache object directly to the caching container.
Cache
There are multiple constructors that provide different ways to load the cached configuration parameters.
Sometimes you may need to use the API to dynamically add the cache, as the example below provides. Download
In addition to the caching that can be configured in the XML file, you can also add Cache Manager.addcache (CacheName) using the API dynamic additions and deletions cache// ;// Use the default configuration to add the cache cachemanager singletonmanager = cachemanager.create (); Singletonmanager.addcache (" Testcache "); Cache test = singletonmanager.getcache ("Testcache");// add the cache with a custom configuration, Note Cachemanager singletonmanager = cachemanager.create () is not available before the cache is added to CacheManager; Cache memoryonlycache = new cache ("Testcache", 5000, false, false, 5, &NBSP;2); Singletonmanager.addcache (Memoryonlycache); Cache test = singletonmanager.getcache ("Testcache");// Add the cache using a specific configuration cachemanager Manager = cachemanager.create (); Cache testcache = new cache ( new cacheconfiguration ("TestCache", MAXENTRIESLOCALHEAP) .memorystoreevictionpolicy (MEMORYSTOREEVICTIONPOLICY.LFU) .eternal (false) . Timetoliveseconds ( .timetoidleseconds) .diskexpirythreadintervalseconds (0) &NBSP;. Persistence (New persistenceconfiguration (). Strategy (Strategy.localtempswap))); manager.addcache ( Testcache);
Delete Cache
Deleting the cache is simple, you just need to pass the specified cache name into the removeCache
method.
CacheManager Singletonmanager = Cachemanager.create (); Singletonmanager.removecache ("sampleCache1");
Implementing basic cache Operations
The two most important methods of the cache are put and get, respectively, to add element and get element.
/** * test: Use the default configuration or use the specified configuration to create a cachemanager * * @author victor zhang */ public class cacheoperationtest { private final logger Log = loggerfactory.getlogger (Cacheoperationtest.class); /** * get CacheManager instances of a singleton using the Ehcache default configuration (Ehcache.xml under Classpath) */ @Test public void operation () { cachemanager manager = cachemanager.newinstance ("src/ Test/resources/ehcache/ehcache.xml "); // get a reference to the cache cache cache = manager.getcache ("UserCache"); // Adding an element to the cache cache.put (New element ("Key1 ", " value1 ")); // Get Element,element class support serialization, So the following two ways can be used element element1 = cache.get ("Key1" ); // gets the non-serialized value log.debug ("key:{}, value:{}", element1.getobjectkey (), element1.getobjectvalue ()); // Get serialized values Log.debug ("key:{}, value:{}", element1.getkey (), element1.getvalue ()); // update the Element cache.put in the cache (new element ("Key1", "value2"); element element2 = cache.get ("Key1"); log.debug ("key:{}, value:{} ", element2.getobjectkey(), element2.getobjectvalue ()); // gets the number of elements in the cache log.debug ("cache size:{}", cache.getsize ()); // get the number of elements in Memorystore Log.debug ("memorystoresize:{}", cache.getmemorystoresize ()); // gets the number of elements of Diskstore log.debug ("diskstoresize:{}", cache.getdiskstoresize ()); // remove element cache.remove ("Key1"); Log.debug ("cache size:{}", cache.getsize ()); // Close the current CacheManager object manager.shutdown (); //&nBSP; Close CacheManager Singleton Example cachemanager.getinstance (). Shutdown (); }}
Spring Consolidated Ehcache Management cache