Getting started with Ehcache
1. Introduction to ehcache
EhCache is a pure Java in-process cache framework, which features fast and efficient. It is the default CacheProvider in Hibernate.
2. ehcache entry instance
1. First, import the jar dependencies related to ehcache. I have demonstrated some maven projects here, So add dependencies in pom. xml.
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.2</version> </dependency>
2. Create the configuration file ehcache. xml. When starting ehcache, it will find the file named ehcache. xml under the root directory of classpath by default. You can also place the file in another location. For convenience, create a configuration file ehcache. xml in src/main/resources/this time.
<? 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 = "120" timeToLiveSeconds = "120" maxEntriesLocalDisk = "10000000" timeout = "120" timeout =" LRU "> <persistence strategy =" localTempSwap "/> </defaultCache> <! -- Helloworld cache --> <cache name = "HelloWorldCache" maxElementsInMemory = "1000" eternal = "false" timeToIdleSeconds = "100" timeToLiveSeconds = "100" overflowToDisk = "false" comment =" LRU "/> </ehcache>
3. Test class
Package com. hz. demo; import net. sf. ehcache. cache; import net. sf. ehcache. cacheManager; import net. sf. ehcache. element; public class EhcacheTest1 {public static void main (String [] args) {// 1. create cache manager CacheManager cacheManager = CacheManager. create (); // 2. obtain the Cache object cache = cacheManager. getCache ("HelloWorldCache"); // 3. create Element element = new Element ("key1", "HelleWorld"); // 4. add the element to the cache. put (element); // 5. obtain the cached Element value = cache. get ("key1"); // 6. the value System in the output cache. out. println ("key1 =" + value. getObjectValue (); // 7. deletes the value cache in the cache. remove ("key1"); // 8. refresh cache. flush (); // 9. disable the cache manager cacheManager. shutdown ();}}
4. output results