Ehcache required for Jar:ehchache-core and spring annotations Spring-context
<dependency> <groupId>net.sf.ehcache</groupId> <artifactid>ehcache-core</artifactid > <version>2.6.6</version></dependency><dependency> <groupId> Org.springframework</groupid> <artifactId>spring-context</artifactId> <version>4.2.7. Release</version></dependency>
Reference notes for Spring-ehcache.xml in the Spring.xml file
Introducing Namespaces xmlns:cache= "Http://www.springframework.org/schema/cache" annotations using cachemanager<!--ehcache config-< Cache:annotation-driven cache-manager= "CacheManager"/> <bean id= "CacheManager" class= " Org.springframework.cache.ehcache.EhCacheCacheManager "p:cache-manager-ref=" Ehcache "/> <!--Ehcache Library Setup--<bean id= "Ehcache" class= "Org.springframework.cache.ehcache.EhCacheManagerFactoryBean" P: config-location= "Classpath:spring/spring-ehcache.xml" p:shared= "true"/>
Spring-ehcache.xml file header The name of the file can be customized, as long as it is introduced into the code
1 "name-optional, unique. Names are used to annotate or differentiate terracotta cluster caches. For the terracotta cluster cache, the combination of the name of the cache manager and the name of the cache can flag a specific cache store in the terracotta cluster cache. 2 "UpdateCheck Update check-an optional Boolean flag that flags whether the cache manager should check the new version of Ehcache over the network. The default is true. 3 "dynamicconfig dynamic configuration-optional. Used to close the dynamic configuration of the cache associated with the cache manager. The default is true, which is dynamic configuration is enabled. Dynamically configured caches can change their tti,ttl and maximum disk space and intrinsic capacity 4 "monitoring monitoring-optional depending on the cache object in the running state. Determines whether the cache manager should automatically register Sampledcachembean to the system Mbean server.
<?xml version= "1.0" encoding= "UTF-8"? ><ehcache xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: nonamespaceschemalocation= "Ehcache.xsd" updatecheck= "true" monitoring= "AutoDetect" dynamicconfig= "true" > </ Ehcache>
<!--cachemanagerpeerproviderfactory Distributed Cache Manager Provider--
propertyseparator Splits the delimiter for the Properties property above peerdiscovery=manual manual cache synchronization peerdiscovery=automatic Broadcast Cache Sync rmiurls refers to the manual detection of the cache address, each time the corresponding cache information is requested, the program will first read the cache from the configured Rmiurls, if there is no cache information, the cache is generated, stored in the corresponding cache of the address and port configured by Cachemanagerpeerlistenerfactory between address and address | (vertical line) to split, url filling rules: //(double slash) the hostname+ configured in the +cachemanagerpeerlistenerfactory property:( Colon) + Port +/(slash) + Cache property name General Rmiurls address information does not contain the address of its own cachemanagerpeerlistenerfactory configuration
<cachemanagerpeerproviderfactory class= "Net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" Properties= "Peerdiscovery=manual, rmiurls=//127.0.0.1:40002/patientcache|//127.0.0.1:40002/menucache|//127.0.0. 1:40002/appcfgcache "propertyseparator=", "/>
<!--cachemanagerpeerlistenerfactory Distributed Cache monitoring factory--
Used to listen for cache replication information in the cluster, where the port information must be the same as the port configured in Cachemanagerpeerproviderfactory, currently not locally related configuration hostname=127.0.0.1 port= 40002 Note: The port number here is not the port number of the Web project, is a custom not occupied port, I myself experiment because the experience was mistaken for the Web project port, the results prompt port conflict
<cachemanagerpeerlistenerfactory class= "Net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" properties= "hostname=127.0.0.1,port=40002,sockettimeoutmillis=2000"/>
<!--specific cache configuration--
Cache attribute Interpretation: must attribute: name: Sets the name of the cache, For the flag cache, the only maxelementsinmemory: the maximum number of objects in memory maxelementsondisk: Maximum number of objects in Diskstore, if 0, no limit eternal: Sets whether the element is permanent, and if it is permanent, timeout ignores overflowtodisk: If the number in memory reaches the limit, save to disk optional property: timetoidleseconds: Set the idle time before the element expires timetoliveseconds: Set the active time before the element expires Diskpersistent: Whether Disk store is persisted on virtual machine startup. The default is false diskexpirythreadintervalseconds: The time to run the disk termination thread, Default is 120 seconds memorystoreevictionpolicy: Policy about eviction Cache child elements: cacheeventlistenerfactory: Registers the appropriate cache listener class, For handling cache events, such as Put,remove,update, and expire Bootstrapcacheloaderfactory: Specifies the appropriate bootstrapcacheloader for initializing the cache, as well as for automatic provisioning.
<!-- Cache expires after 12 hours, and if 12 hours are not accessed, the cache will fail --> <cache name= "Patientcache" Maxentrieslocalheap= "10000" eternal= "false" timetoidleseconds= "43200" timetoliveseconds= "43200" > <cacheEventListenerFactory class= "Net.sf.ehcache.distribution.RMICacheReplicatorFactory" properties= "replicateasynchronously=false, replicateputs=true, replicatePutsViaCopy=true, replicateUpdates=true, &nbsP;replicateupdatesviacopy=true, replicateremovals=true " /> </cache>
Read/Generate Cache @cacheable
The result can be cached based on the request parameters of the method. That is, when the method is called repeatedly using the same parameters, the method itself is not invoked to execute, that is, the method itself is skipped, instead the result of the method is found directly from the cache and returned.
Value: The cache location name, cannot be empty, if using Ehcache, is the namekey of the cache declared in Ehcache.xml: the cached key (guaranteed unique parameter), the default is null, both means using the method parameter type and parameter value as key, support Spel Cache key can also be composed of the following rules, when we want to use root as key, we can not write root directly @cache (key= "Caches[1].name"). Because he defaults to using #root's 1.methodName current method name #root .methodname 2.method Current methods #root. Method.name 3.target currently used objects #root .target 4.targetClass currently called object class#root.targetclass 5.args Array of current method parameters #root .args[0] 6.caches The cache used by the currently invoked method #root. Caches[0],name 7. Method parameters assumed to contain string parameters str #str #p0代表方法的第一个参数 assumes the httpservletrequest type parameter request #request. getattribute (' usId32 ') Methods to invoke parameters related to an incoming parameter object Assume that the user type parameter user is included #user .usid The 8 method of the call into the parameter object can be directly used in this form. String ' string content ' condition: Trigger condition, only when the condition is satisfied, the cache is added, the default is empty, both means that all are added to the cache, support Spel
Java code example
@Cacheable (value= "Patientcache", key= "#hosId + ' _ ' + #request. getattribute (' usId32 ') + ' _ ' + ' patientlist '") @ Requestmapping (value = "/{hosid}/20004/005", method = Requestmethod.post, produces = "application/json;charset=utf-8") @ResponseBodypublic resultvo listpats (@PathVariable Long hosid,httpservletrequest request) {}
Delete Cache @cacheevict
Uniquely finds cache records based on value and key values, and cleans up cache information
Value: The location of the cache, cannot be empty. Key: The cached key, which is empty by default. Condition: Triggered condition, only the condition will be clear cache, default is empty, support Spel. Allentries:true indicates that all caches in value are cleared (which can be interpreted as emptying the table), and the default is False (deleting a single piece of data). Beforeinvocation: When we set to true, spring clears the cache before calling the method. The purge operation is triggered by default after the method executes successfully.
Java code example
@CacheEvict (value= "Patientcache", key= "#hosId + ' _ ' + #usId32 + ' _ ' + ' PatientList '") @RequestMapping (value= "/{hosid}/{ Usid32}/frushpatlistcache ", method=requestmethod.post,produces =" Application/json;charset=utf-8 ") @ responsebodypublic void Freashpatlistcache (@PathVariable Long hosid, @PathVariable String usid32,httpservletresponse Response,httpservletrequest request) {Loggerutil.debug (logger, "Patient cache information Cleanup Frushpatlistcache" cleans up the cache structure for a user's patient list method, Into the method body ");}
Update Cache @CachePut
Although it can also declare a method to support caching, it does not check the cache for the existence of previously executed results, but executes the method each time and puts the execution result into the specified cache before executing the method.
Value: The location of the cache, cannot be empty. Key: The cached key, which is empty by default. Condition: Triggered condition, only the condition will be clear cache, default is empty, support Spel.
Java code example
@CachePut (value= "Patientcache", key= "#hosId + ' _ ' + #usId32 + ' _ ' + ' PatientList '") @RequestMapping (value= "/{hosid}/{ Usid32}/frushpatlistcache2 ", method=requestmethod.post,produces =" Application/json;charset=utf-8 ") @ responsebodypublic void FreashPatListCache2 (@PathVariable Long hosid, @PathVariable String usid32,httpservletresponse Response,httpservletrequest request) {Loggerutil.debug (logger, "Patient cache information Cleanup Frushpatlistcache" cleans up the cache structure for a user's patient list method, Into the method body ");}
Resources
Dive into the use of EhCache cache systems in a clustered environment
Http://www.ehcache.org/ehcache.xml translation
This article is from the "Fingertip Maniac" blog, please be sure to keep this source http://tianyang10552.blog.51cto.com/7380722/1899550
Distributed cache configuration in the form of Spring-ehcache RMI