Springehcache must be known before using spring cache and ehcache.

Source: Internet
Author: User

Springehcache must be known before using spring cache and ehcache.

I haven't written a blog for a long time. I really don't have time. Ps: Actually, it's just lazy !! The next few articles will write down the cache. Here we will mainly write down the content of ehcache and spring integration, including the cache in the form of aop, the cache based on annotations, and the page cache. Learn about spring cache and ehcache before doing so !!

 

This blog.

I. spring cache

Spring Cache is used in methods. Its core idea is as follows: when we call a cache method, we store the method parameters and returned results as a key-value pair in the cache, when the same parameter is used to call the method next time, the method will not be executed, but the result will be directly obtained from the cache for return. Therefore, when using Spring Cache, we must ensure that the cached methods have the same response results for the same method parameters. Using Spring Cache requires us to do two things:1.Declare some methods to use Cache 2. Configure Spring support for Cache

Spring provides several annotations to support Spring Cache. Its core is @ Cacheable and @ CacheEvict. The method marked with @ Cacheable will Cache the returned results after execution. The method marked with @ CacheEvict will remove some elements in Spring Cache before or after the method is executed.

Here we only introduce several common attributes.

Annotation-based concepts:

1. @ Cacheable
You can mark a method or a class. When marked on a method, it indicates that the method supports caching. When marked on a class, it indicates that all the methods of this class support caching. For a caching method, Spring caches its return value after it is called to ensure that the method can be directly obtained from the cache next time it uses the same parameters, you do not need to execute this method again. Spring caches the return values of the cache method based on key-value pairs, and the value is the return results of the method. For keys, Spring supports two policies, default and custom.
Note that the caching function is not triggered when a method that supports caching is called inside the object. @ Cacheable three attributes can be specified: value, key, and condition.

2. @ CachePut
In an environment that supports Spring Cache, Spring checks whether Cache elements with the same key exist in the Cache before each execution of the @ Cacheable annotation method, if this method does not exist, the system retrieves results from the cache and returns the results. Otherwise, the system executes the operation and saves the returned results to the specified cache. @ CachePut can also declare that a method supports the caching function. Unlike @ Cacheable, the method marked with @ CachePut does not check whether the cache has previously executed results before execution, but executes this method every time, the execution results are stored in the specified cache as key-value pairs.
@ CachePut can also be labeled on classes and methods. When @ CachePut is used, we can specify the same attributes as @ Cacheable.
3. @ CacheEvict
@ CacheEvict is used to mark the methods or classes on which cache elements need to be cleared. When it is marked on a class, it indicates that all the methods will trigger the cache clearing operation. @ CacheEvict the attributes that can be specified include value, key, condition, allEntries, and beforeInvocation. The semantics of value, key, and condition is similar to that of @ Cacheable. That is, value indicates the Cache on which the cleanup operation is performed (corresponding to the Cache name); key indicates the key to be cleared. If not specified, the key generated by the Default policy is used; condition indicates the condition in which the operation is cleared.
 
Attribute 1: Value

It must be specified. It indicates the Cache on which the return value of the current method will be cached. The corresponding Cache name is <cache name = "myCache"/> In ehcache. xml. It can be a Cache or multiple caches. When multiple caches need to be specified, it is an array.
Attribute 2: Key

Cache Key. If this attribute is not specified, Spring uses the Default policy to generate a key (indicating that the parameter type and value of the method are used as the key ), the key attribute is used to specify the key corresponding to the returned results of the Spring cache method. This attribute supports SpringEL expressions. We can also customize policies: custom policies mean that we can use Spring EL expressions to specify our keys. Here, EL expressions can use method parameters and their corresponding attributes. When using method parameters, we can directly use "# parameter name" or "# p parameter index"
There are two key generation policies: one is the Default policy and the other is the custom policy.
The default key generation policy is generated by KeyGenerator. the Default policy is as follows:
1. If the method does not have a parameter, 0 is used as the key.
2. If there is only one parameter, use this parameter as the key.
3. If one parameter is redundant, use the hashCode of all parameters as the key.
2. custom policies refer to the use of Spring EL expressions to specify our keys. Here, EL expressions can use method parameters and their corresponding attributes. When using method parameters, we can directly use "# parameter name" or "# p parameter index
Attribute 3: Condition

Sometimes we may not want to cache all the returned results of a method. This function can be implemented through the condition attribute.
The condition attribute is empty by default, indicating that all calls will be cached. The value is specified through the SpringEL expression. If it is set to true, it indicates cache processing; if it is set to false, it indicates no cache processing, that is, this method is executed every time this method is called. The following example indicates that the cache is performed only when the user id is an even number.
@ Cacheable (value = {"users"}, key = "# user. id", condition = "# user. id % 2 = 0 ")
Public User find (User user ){
System. out. println ("find user by user" + user );
Return user;
}
Attribute 4: AllEntries

Is boolean, indicating whether to clear all elements in the cache. The default value is false, indicating no need. When allEntries is set to true, Spring Cache ignores the specified key. Sometimes we need to Cache all the elements, which is more efficient than clearing one element at a time.
@ CacheEvict (value = "users", allEntries = true)
Public void delete (Integer id ){
System. out. println ("delete user by id:" + id );
}
Attribute 5: BeforeInvocation

By default, the clear operation is triggered after the corresponding method is successfully executed. That is, if a method fails to return a result because of an exception thrown, the clear operation is not triggered. BeforeInvocation can be used to change the time when the cleanup operation is triggered. When the attribute value is set to true, Spring clears the specified elements in the cache before calling this method.
@ CacheEvict (value = "users", beforeInvocation = true)
Public void delete (Integer id ){
System. out. println ("delete user by id:" + id );
}

Note:We can also use the removal policy of ehcache to recently use the (LRU) "policy. Other methods include first-in-first-out (FIFO), least LFU, and least LRU.

Annotation-Based Configuration:

To configure Spring's support for annotation-based Cache, first we need to introduce the cache namespace in the Spring configuration file, and then use the <cache: annotation-driven/> enables Spring to support annotation-based Cache.

<Cache: annotation-driven/> has a mode attribute. The optional values include proxy and aspectj. Proxy is used by default. When the mode is proxy, Spring Cache takes effect only when the Cache method is called externally, this means that if a Cache method is called within the declared object, Spring Cache will not function. This problem does not occur when mode is aspectj. In addition, only the @ Cacheable Annotation on the public method works when using the proxy. If you need a method other than the public method, you can also set the mode to aspectj when using Spring Cache. In addition, <cache: annotation-driven/> can also specify a proxy-target-class attribute to indicate whether a proxy class is required. The default value is false. The @ Cacheable and @ cacheEvict mentioned above can also be labeled on the interface, which is no problem for the interface-based proxy, however, when we set proxy-target-class to true or mode to aspectj, the operation is performed directly based on the class, the @ Cacheable and other Cache annotations defined on the interface will not be identified, and the corresponding Spring Cache will not work.

Note that <cache: annotation-driven/> only searches for cache annotations such as @ Cacheable defined in the same ApplicationContext.

XML-Based Configuration:
 1 <cache:advice id="cacheAdvice" cache-manager="cacheManager"> 2  3       <cache:caching cache="users"> 4  5          <cache:cacheable method="findById" key="#p0"/> 6  7          <cache:cacheable method="find" key="#user.id"/> 8  9          <cache:cache-evict method="deleteAll" all-entries="true"/>10 11       </cache:caching>12 13    </cache:advice>

The above configuration defines a cache: advice named cacheAdvice, which specifies to cache the findById and find methods to the cache named users. The method can also use the wildcard "*". For example, "find *" indicates any method starting with "find. With cache: advice, we also need to introduce the aop namespace, and then use aop: config to specify the pointcut on which the defined cacheAdvice will be applied. For example:

1    <aop:config proxy-target-class="false">2 3       <aop:advisor advice-ref="cacheAdvice" pointcut="execution(* com.xxx.UserService.*(..))"/>4 5    </aop:config>

 

Ii. EhCacheIt is a pure Java in-process cache framework and features fast and efficient.

Ehcache Official Website: http://www.ehcache.org/can download the document to see, it is very clear to write.

Main features: 1. fast 2. simple 3. multiple cache policies 4. there are two levels of cached data: memory and disk, so there is no need to worry about capacity issues 5. cached data is written to the disk during VM restart. 6. you can use RMI, insert API, and other methods for Distributed caching. 7. listening interface with cache and cache manager 8. supports multiple cache manager instances and multiple cache regions of one instance. provides Hibernate cache for ehcache. xml: The annotations are clearly written.
<DiskStore>: when the number of objects in the memory cache exceeds maxElementsInMemory, the cached objects are written to the disk cache (Object serialization interface is required)
<DiskStore path = "">: used to configure the physical path used by the disk cache. The file suffix used by the Ehcache disk cache is *. data and *. index.
Name: "cache name, the unique identifier of the cache (ehcache will put this cache in HashMap)
MaxElementsInMemory: Maximum number of caches.
Eternal = "false": whether the object is permanently valid. If this parameter is set, timeout does not work. (Required)
MaxEntriesLocalHeap = "1000": Maximum number of cache objects in heap memory. No limit is set for 0 (required)
MaxEntriesLocalDisk = "1000": Maximum number of Hard Disk caches.
OverflowToDisk = "false": Specifies whether to enable disk caching when the cache reaches the maxElementsInMemory value (which must be set .)
DiskSpoolBufferSizeMB: this parameter sets the cache size of DiskStore (disk cache. The default value is 30 MB. Each Cache should have its own buffer.
DiskPersistent = "false": whether the disk cache is retained during JVM restart (false by default)
TimeToIdleSeconds = "0": the access interval (in seconds) that causes the element to expire. That is, when the cache is idle for n seconds, it is destroyed. This attribute is valid only when eternal is false. 0 indicates that it can be permanently idle. The default value is 0.
TimeToLiveSeconds = "600": the time when an element exists in the cache (in seconds). That is, when the cache is alive for n seconds, it is destroyed. 0 indicates that it will never expire.
MemoryStoreEvictionPolicy = "LFU": When maxElementsInMemory is reached, how to force eviction by default the "recently used (LRU)" policy is used. Others also include first-in-first-out FIFO, with at least LFU used, LRU is rarely used.
DiskExpiryThreadIntervalSeconds: Specifies the interval for running a disk failure thread. The default value is 120 seconds.
ClearOnFlush: whether to clear when the maximum number of memory is exceeded.
<?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">        <diskStore path="java.io.tmpdir"/>        <defaultCache            maxEntriesLocalHeap="10000"            eternal="false"            overflowToDisk="false"             timeToIdleSeconds="120"            timeToLiveSeconds="120"            diskSpoolBufferSizeMB="30"            maxEntriesLocalDisk="10000000"            diskExpiryThreadIntervalSeconds="120"            memoryStoreEvictionPolicy="LRU">        <persistence strategy="localTempSwap"/>    </defaultCache>       <cache name="myCache"           maxEntriesLocalHeap="10000"           maxEntriesLocalDisk="1000"           eternal="false"           diskSpoolBufferSizeMB="30"           timeToIdleSeconds="300"           timeToLiveSeconds="600"           memoryStoreEvictionPolicy="LFU"           transactionalMode="off">        <persistence strategy="localTempSwap"/>    </cache>   </ehcache>
 
 

Well, here we will only introduce the basis of Spring cache and ehcache. Next I will introduce examples, AOP-based cache implementation, annotation-based cache implementation, and page cache. If you cannot write well, please correct me !!

 

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.