Simple and practical Ehcache and simple and practical ehcache
The following is an Ehcache. xml configuration file;
A general cache policy can be used;
1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <ehcache xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" 3 xsi: noNamespaceSchemaLocation = "http://ehcache.org/ehcache.xsd" 4 updateCheck = "false"> 5 6 <! -- 7 diskStore: cache path. ehcache is divided into two levels: memory and disk. This attribute defines the disk cache location as 8 users. home-user main directory 9 user. dir-the user's current working directory 10 java. io. tmpdir-default temporary file path 11 --> 12 <diskStore path = "java. io. tmpdir/Tmp_Ehcache "/> 13 <! -- 14 name: cache name. 15 maxElementsInMemory: Maximum number of caches 16 maxElementsOnDisk: Maximum number of Hard Disk caches. 17 eternal: whether the object is permanently valid. Once set, timeout does not work. 18 overflowToDisk: whether to save to the disk. When the system is running, 19 timeToIdleSeconds: sets the allowed idle time (in seconds) before the object expires ). This attribute is optional only when the eternal = false object is not permanently valid. The default value is 0, indicating that the idle time is infinite. 20 timeToLiveSeconds: sets the allowed lifetime of an object before it expires (unit: seconds ). The maximum time is between the creation time and the expiration time. It is used only when the eternal = false object is not permanently valid. The default value is 0. That is, the object survival time is infinite. 21 diskPersistent: Whether to cache data during VM restart Whether the disk store persists between restarts of the Virtual Machine. the default value is false.22 diskSpoolBufferSizeMB: this parameter sets The cache size of DiskStore (disk cache. The default value is 30 MB. Each Cache should have its own buffer. 23 diskExpiryThreadIntervalSeconds: The interval between running threads with disk failures. The default value is 120 seconds. 24 memoryStoreEvictionPolicy: When the maxElementsInMemory limit is reached, Ehcache clears the memory according to the specified policy. The default policy is LRU (least recently used ). You can set it to FIFO (first-in-first-out) or LFU (rarely used ). 25 clearOnFlush: whether to clear when the maximum memory size is exceeded. 26 memoryStoreEvictionPolicy: optional policies include LRU (minimum recently used, default policy), FIFO (first-in-first-out), and LFU (minimum number of visits ). 27 FIFO, first in first out, which is the most familiar and advanced. 28 LFU and Less Frequently Used are the strategies Used in the above example. To put it bluntly, they are least Used. As mentioned above, the cached element has an hit attribute, and the minimum hit value will be cleared out of the cache. 29 LRU, Least Recently Used, Least Recently Used. The cached element has a timestamp. When the cache capacity is full and you need to make room to cache new elements, the elements whose timestamp is the farthest from the current time in the existing cache will be cleared out of the cache. 30 --> 31 <defaultCache32 eternal = "false" 33 maxElementsInMemory = "1000" 34 overflowToDisk = "false" 35 diskPersistent = "false" 36 timeToIdleSeconds = "0" 37 timeToLiveSeconds = "600 "38 memoryStoreEvictionPolicy =" LRU "39/> 40 <cache41 name =" demo "42 eternal =" false "43 maxElementsInMemory =" 100 "44 overflowToDisk =" false "45 diskPersistent =" false "46 timeToIdleSeconds =" 0 "47 timeToLiveSeconds =" 300 "48 memoryStoreEvictionPolicy =" LRU "49/> 50 51 </ehcache>
View Code
In fact, cache is nothing more than reducing database query operations. Next, let's briefly describe how to use it in the code,
Configure ehcache to spring (spring-boot is used below)
Package com. config; import org. springframework. cache. annotation. enableCaching; import org. springframework. cache. ehcache. ehCacheCacheManager; import org. springframework. cache. ehcache. ehCacheManagerFactoryBean; import org. springframework. context. annotation. bean; import org. springframework. context. annotation. configuration; import org. springframework. core. io. classPathResource; import javax. persistence. cache;/*** Created by ding on 2017-04-25. * // @ Configuration @ EnableCaching // tag Start cache public class CacheConfiguration {// ehcache main manager EhcacheManager @ Bean public handler () {export factoryBean = new EhCacheManagerFactoryBean (); factoryBean. setConfigLocation (new ClassPathResource ("ehcache. xml "); factoryBean. setShared (true); // This indicates whether the cache base is dedicated to Spring or shared with other (such as hibernate Ehcache) return factoryBean ;} @ Bean public EhCacheCacheManager ehCacheCacheManager (EhCacheManagerFactoryBean factoryBean) {System. out. println ("CacheConfiguration. ehcacheManager () "); return new EhCacheCacheManager (factoryBean. getObject ());}}
Note that the value in the java code @ cacheAble annotation corresponds to the name attribute of the cache defined in ehcache. xml (the default configuration is used if no value is found)
@ CacheAble the key in the annotation is the cached key. when calling the method, it determines whether to enter the method based on whether the key exists in the cache.
Note: @ cacheable annotations can only be used in implementation classes and cannot be used in interfaces !!!
@ Servicepublic class InfoServiceImpl {// value Attribute indicates which cache policy is used. The cache policy is stored in ehcache. in xml, // LRU (minimum recently used, default policy), FIFO (first-in-first-out), LFU (minimum number of visits) public static final String DEMO_CACHE_NAME = "demo "; // This demo corresponds to the name in ehcache. // each key must contain no less single quotes. Otherwise, it will be recognized as an object @ Cacheable (value = DEMO_CACHE_NAME, key = "'info _ '+ # id") public String findNameById (Integer id ){
// Cacheable does not have this key before entering the method System. out. println ("no cache:" + id); return "zhangsan" ;}@ CacheEvict (value = DEMO_CACHE_NAME, key = "'info _ '+ # id ") // clear cache: This key is used to clear the cache. If the corresponding key is not found, the public void delete (Integer id) {// delete database ...... (Omitted)} @ CachePut (value = DEMO_CACHE_NAME, key = "'info _ '+ # infos. getId ()") public String update (String str ){/*
@ CachePut indicates re-storing the cache object. no matter whether the key is cached or not, the method will be entered.
*/Return str ;}}