Spring Integrated Ehcache Local cache

Source: Internet
Author: User

1.maven Dependency

       <!--Ehcache Related Dependencies -        <Dependency>            <groupId>Net.sf.ehcache</groupId>            <Artifactid>Ehcache</Artifactid>            <version>2.8.2</version>        </Dependency>
Ehcache

2. Configuring the Ecache.xml Configuration

<EhcacheXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:nonamespaceschemalocation= "Http://ehcache.org/ehcache.xsd"UpdateCheck= "false">    <!-- Name: Cache names.            Maxelementsinmemory: Maximum number of caches Maxelementsondisk: Maximum number of hard disk caches.            Eternal: The object is permanently valid, but if set, timeout will not work. Overflowtodisk: Whether to save to disk when the system is timetoidleseconds: sets the allowable idle time (in seconds) before the object expires.            An optional property is used only if the Eternal=false object is not permanently valid, and the default value is 0, which means that the idle time is infinite. Timetoliveseconds: Sets the time (in seconds) that an object is allowed to survive before it expires. The maximum time is between the creation time and the expiration time.            Used only when the Eternal=false object is not permanently valid, the default is 0, which means that the object survives indefinitely. Diskpersistent: Whether to cache VM Restart period data whether the disk store persists between restarts of the virtual machine.            The default value is False. DISKSPOOLBUFFERSIZEMB: This parameter sets the buffer size of the Diskstore (disk cache). The default is 30MB.            Each cache should have its own buffer.            Diskexpirythreadintervalseconds: Disk failed thread run time interval, default is 120 seconds. Memorystoreevictionpolicy: When the maxelementsinmemory limit is reached, Ehcache will clean up the memory according to the specified policy.            The default policy is LRU (least recently used).            You can set it to FIFO (first in, out) or LFU (less used).            Clearonflush: If the maximum amount of memory is cleared.            Memorystoreevictionpolicy: The optional policies are: LRU (least recently used, default policy), FIFO (first in, out), LFU (minimum number of accesses). Fifo,first in firstOut, this is the most well-known, first-out. LFU, less frequently used, is the strategy used in the above example, and it is straightforward to say that it has been used at least for a long time.            As mentioned above, the cached element has a hit attribute, and the least hits value will be cleared out of the cache.  Lru,least recently used, the least recently used, the cached element has a timestamp, and when the cache is full, and you need to make room to cache the new element, the elements in the existing cache element with the longest timestamp from the current time are cleared out of the cache. -    <Cachename= "TestInfo"Eternal= "false"maxelementsinmemory= "+"Overflowtodisk= "false"diskpersistent= "false"Timetoidleseconds= "0"Timetoliveseconds= "0"Memorystoreevictionpolicy= "LFU"/></Ehcache>
Ecache.xml

3. In the Spring container integration Ecache

<!--ehcache Configuration--
<!--declare a cache manager (Ehcachecachemanager) The implementation code here is implemented by passing in the CacheManager instance of the Ehcache.
<bean id= "Ehcache"
class= "Org.springframework.cache.ehcache.EhCacheManagerFactoryBean" >
<property name= "configlocation" value= "Classpath:ehcache.xml"/>
</bean>
<bean id= "CacheManager" class= "Org.springframework.cache.ehcache.EhCacheCacheManager" >
<!--Specify the Ehcache profile path--
<property name= "CacheManager" ref= "Ehcache"/>
</bean>
<!--enable note-Driven caching--
<cache:annotation-driven cache-manager= "CacheManager"/>

Note the cache tag

Annotations for 4.spring

In fact, Ehcache is using spring cache annotations.

1.1 @Cacheable
@Cacheable can be marked on a method or on a class. When tagged on a method means that the method is cached, and when tagged on a class It means that all methods of the class are cache-enabled. For a cache-enabled method, spring caches its return value after it is called, ensuring that the next time the same parameter is used to execute the method, the result can be obtained directly from the cache without having to execute the method again. Spring caches the return value of the method as a key-value pair, and the value is the return result of the method, and spring supports two strategies, the default policy and the custom policy, which are explained later. It is important to note that caching is not triggered when a caching-enabled method is invoked inside the object. @Cacheable can specify three properties, value, key, and condition.

1.1.1 The Value property specifies the cache name
The Value property must be specified, which means that the return value of the current method is cached on which cache, corresponding to the name of the cache. It can be a cache or multiple caches, which is an array when multiple caches need to be specified.

   @Cacheable("cache1")//Cache是发生在cache1上的   public User find(Integer id) {      return null;   }    @Cacheable({"cache1", "cache2"})//Cache是发生在cache1和cache2上的   public User find(Integer id) {      return null;   }

1.1.2 Using the key property to customize the key
The key property is used to specify the key that corresponds to the return result of the spring cache method. This property supports Springel expressions. When we do not specify this property, spring uses the default policy to generate the key. Let's take a look at the custom policy here, as the default policy is described separately later in this article.
The custom policy is that we can specify our key through the El expression of spring. The El expressions here can use the method parameters and their corresponding properties. We can use "#参数名" or "#p参数index" directly when using method parameters. Here are a few examples of using parameters as keys.

  @Cacheable(value="users", key="#id")  public User find(Integer id) {     return null;  }  @Cacheable(value="users", key="#p0")  public User find(Integer id) {     return null;  }  @Cacheable(value="users", key="#user.id")  public User find(User user) {     return null;  }  @Cacheable(value="users", key="#p0.id")  public User find(User user) {     return null;  }

In addition to the above usage parameters as key, Spring also provides us with a root object that can be used to generate the key. The root object allows us to obtain the following information.

Paste_image.png

We can also omit "#root" when we want to use the root object's property as key, because spring uses the root object's properties by default. Such as:

  @Cacheable(value={"users", "xxx"}, key="caches[1].name")  public User find(User user) {        return null;  }

1.1.3 Condition property specifies the condition that occurs
Sometimes we may not want to cache a method with all of the returned results. This functionality can be achieved through the condition property. The Condition property defaults to NULL, which means that all invocation scenarios are cached. The value is specified by the Springel expression, which is true when the cache is processed, and when false indicates that no caching is processed, that method executes once each time the method is called. The following example indicates that caching occurs only if the ID of the user is even.

  @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;  }

1.2 @CachePut
In a spring cache-enabled environment, for a method that uses the @cacheable annotation, spring checks to see if there is a cache element of the same key in the cache before each execution, and if it does not execute the method, it returns the result directly from the cache. Otherwise it will execute and the returned result will be stored in the specified cache.
@CachePut can also declare a method that supports caching functionality. Unlike @cacheable, a method that uses the @cacheput annotation does not check the cache for previous results before execution, but instead executes the method every time and deposits the execution result (the return value) in the specified cache as a key-value pair. Therefore, there must be a return value, and no return value will be placed in the new cache.
@CachePut can also be labeled on the class and on the method. The properties we can specify when using @cacheput are the same as @cacheable.

  @CachePut("users")//每次都会执行方法,并将结果存入指定的缓存中  public User find(Integer id) {     return user;  }

1.3 @CacheEvict
The @CacheEvict is used to label the method or class on which the cache element needs to be cleared. When marked on a class, the execution of all the methods in it indicates that the cached purge operation is triggered. @CacheEvict properties that can be specified are value, key, condition, allentries, and Beforeinvocation. The semantics of value, key, and condition are similar to those of the @cacheable counterparts. That is, value indicates which cache (corresponding to the cache name) The purge operation occurred on, and key indicates which key needs to be purged, and key;condition generated using the default policy, if unspecified, represents the condition in which the purge operation occurs. Let's take a look at the new two properties Allentries and Beforeinvocation.
1.3.1 Allentries Properties
Allentries is a Boolean type that indicates whether all elements in the cache need to be cleared. The default is false, which means it is not required. When Allentries is specified as true, the Spring cache ignores the specified key. Sometimes we need the cache to clear all the elements, which is more efficient than a clear element.

  @CacheEvict(value="users", allEntries=true)  public void delete(Integer id) {     System.out.println("delete user by id: " + id);  }

1.3.2 Beforeinvocation Properties
The purge operation is triggered by default after the corresponding method executes successfully, that is, the method does not trigger a purge operation if it fails to return successfully because it throws an exception. Using Beforeinvocation can change the time that the purge operation is triggered, and when we specify that the property value is true, spring clears the specified element in the cache before calling the method.

  @CacheEvict(value="users", beforeInvocation=true)  public void delete(Integer id) {     System.out.println("delete user by id: " + id);  }

In fact, in addition to using @cacheevict to clear the cache element, when we use Ehcache as the implementation, we can also configure the Ehcache own eviction policy, which is specified by the Ehcache configuration file.
1.4 @Caching
@Caching annotations Allow us to specify multiple spring cache-related annotations at the same time on a method or class. It has three properties: cacheable, put, and evict, which are used to specify @cacheable, @CachePut, and @cacheevict, respectively.

   @Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),         @CacheEvict(value = "cache3", allEntries = **true**) })   **public** User find(Integer id) {      **return****null**;   }

3.1 Key's default policy
The default key generation policy is generated by Keygenerator with the following default policy:

    • If the method has no arguments, 0 is used as the key.
    • Use this parameter as key if there is only one argument.
    • If the argument is extra, use the hashcode of all parameters as key.

If we need to specify our own default policy, then we can implement our own keygenerator and then specify the keygenerator that our spring cache uses to define our own keygenerator.
When using annotation-based configuration, it is specified by Cache:annotation-driven.

   <cache:annotation-driven key-generator=*"userKeyGenerator"*/>     <bean id="userKeyGenerator" class="com.xxx.cache.UserKeyGenerator"/>

The use of XML-based configuration is specified by Cache:advice.

   <cache:advice id="cacheAdvice" cache-manager="cacheManager" key-generator="userKeyGenerator">   </cache:advice>

Points:
In fact, Ehcache is using the spring cache annotations, it is important to note that when a caching-enabled method is invoked inside the object, the cache function is not triggered.
@Cacheable parameter: value refers to which cache is cached, key refers to the cache method's return result corresponding to the key,condition refers to what the case caches.
@Cacheable If the same key is found in the cache, the data is taken from the cache. The @CachePut is re-executed each time, and the results are put into the cache. @CacheEvict indicates that the cache is cleared.
If no key is specified. This is the default policy with key (using parameters), or you can customize the key generation strategy.



Bluebule
Links: https://www.jianshu.com/p/db110523a387
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

Spring Integrated Ehcache Local cache

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.