spring cache code details

  • 2021-01-25 07:28:49
  • OfStack

This paper focuses on spring caching, which is described as follows.

This article is roughly modified according to Google translation, because the original text does not know what language, so may lead to the translation of mistakes and inaccurate places, but the general direction of the feeling is quite good, so here sorted out 1, hope to be helpful.

Cache 1 is a great need for both of these to improve application performance and reduce its workload. Furthermore, its usefulness today is particularly obvious and can be made to handle thousands of visitors to the concurrents.D'un architecture on the Web application, cache management is orthogonal to the business logic of the application and for this reason should have minimal impact on the development of the application itself. Starting with version 3.1, Spring provides API for cache management, similar to declarative transaction management. An abstract interface to caching, all of which uses different caching solutions with minimal code impact.

spring uses the Java method to request a combination of parameters to a method for the first time, and spring stores the return value in the cache. Therefore, the next request will be to use the value directly from the cache without having to call a potentially costly method. Everything is applied transparently and does not affect the method being called.
In this article, we will look at two different implementations of cache stores from Spring.

The Java ConcurrentHashMap Ehcache

implementation

The integration of spring and caching is simple and transparent, with the @Cacheable annotation indicating the methods that require caching


@Cacheable(value= "dataCache")  
public Reponse getDatas(Long param1, String param2){ } 

ES35en is the name of the associated cache. The first time this method is called, the method executes and stores the result of the execution to < Parameter one, parameter two > The hashed key is the result set of the result, and the method does not need to be executed again when called again with the same parameters.

It is possible that more than one cache is associated with our method


@Cacheable({"dataCache", " default " })   
public Reponse getDatas(Long param1, String param2){  } 

In this case, each cache is checked before the method executes, and if there is a hit, the associated value is returned.

Generate cache key

The base algorithm of 1 cache manager is small. A cache can be thought of as a memory area in which the objects stored are mapped by a one-only secret key. The process of object search is as follows:

1. Calculate key (obtain hashcode by using hash method)
2, Find the object according to key value
3, Returns the result if an object is found
4. If it cannot be found, the actual key associated with the object is calculated and the object is stored in the appropriate location

spring uses a simple hash that generates the key based on the method parameters passed in

Custom cache

The target method cannot simply generate different key based on the parameters, only a few simple cases are generated based on the parameters


@Cacheable(value= "dataCache")   
public Reponse getDatas(Long param1, String param2, boolean param3){  } 

ES76en allows developers to specify how ES77en is generated, which can be done using ES78en expressions


@Cacheable(value= "dataCache", key="#param2")   
public Reponse getDatas(Long param1, String param2, boolean param3){   } 

In this case, the parameter of the secret key computed by the cache is simply Parma2

ES86en also allows the use of nested attributes


@Cacheable(value="dataCache", key=#param2.name")  
 public Reponse getDatas(Long param1, Data param2, boolean param3){} 

This case is the secret key calculated according to the name attribute of Parma2

Conditions of the cache

There is one cache that may not be applicable to the cache in the used case, but it is needed in some cases. When caching, it is processed according to the true or false value of the SPEL expression. If the condition is true, it is cached


@Cacheable(value= "dataCache", key="#param2", condition="#param2.length<64")   
public Reponse getDatas(Long param1, String param2, boolean param3){  } 

In this case, the cache is only used if the length of the second parameter is less than 64

@ CacheEvict annotations

The spring cache can not only cache the data but also clear the cache of 1 cache store. This procedure is used to remove stale data or unused cached data. The annotation @CacheEvict defines methods to perform cache cleanup, which are triggers to delete data from the cache.


@CacheEvict(value= "dataCache")   
public void reloadData(){  } 

This option is necessary when a cache of data needs to be cleared.

Enable the cache

To enable caching support for a single spring project, we need to add a comment to the cache on the namespace


<beans xmlns="http://www.springframework.org/schema/beans"     
    xmlns:cache="http://www.springframework.org/schema/cache"     
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     
    xmlns:context="http://www.springframework.org/schema/context"     
    xsi:schemaLocation="http://www.springframework.org/schema/beans       
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd       
    http://www.springframework.org/schema/cache       
    http://www.springframework.org/schema/cache/spring-cache.xsd       
    http://www.springframework.org/schema/context">   
  
<cache:annotation-driven /> 

Removing annotations can disable caching or enable the use of caching in our configuration class


@Configuration   
@EnableCaching   
public class AppConfig {  } 

Technical limitations

The argument to the object pass method must have its own hashcode method to calculate the secret key

The object passed and returned as a parameter should be serializable

Implementation choice

spring provides two basic implementations:

The java concurrentHashMap Ehcache

To use them, you only need to declare the appropriate CacheManger and manager entities

ConcurrentHashMap using java


<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">   
<span style="white-space:pre">  </span><property name="caches">   
<span style="white-space:pre">    </span><set>   
<span style="white-space:pre">      </span><bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" name="default"/>   
<span style="white-space:pre">      </span><bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" name="dataCache"/>   
<span style="white-space:pre">    </span></set>   
<span style="white-space:pre">  </span></property>   
</bean> 

Each Manger requires a name to be identified by comments. One can manage multiple SimpleCacheManger from one Manger, and this implementation requires very little external library.

Implement Ehcache

The statement CacheManger


@Cacheable({"dataCache", " default " })   
public Reponse getDatas(Long param1, String param2){  } 
0

In ehcache.xml a file is an application cache parameter file:


@Cacheable({"dataCache", " default " })   
public Reponse getDatas(Long param1, String param2){  } 
1

Using ehcache, we can define multiple caches for different parameters in a very simple way

Name: Identifier for the cache

maxBytesLocalHeap: Defines the number of bytes that the cache can use for virtual machines. If 1 CacheManager maxBytesLocalHeap has been set, the cache's determined size will be subtracted from the CacheManager. Other caches share the rest. The value of this property is data < Serial number > K | K | M | M | G | G representative kilobytes (K | K), megabytes (M | M) or gigabytes (G | G).

Timeless: Defines whether an element is eternal. If this is the case, timeouts will be ignored and the item is never expired.
timeToIdleSeconds: This is the number of seconds that the project has seen since its last utilisation. The default value of La is 0, and the element remains static
timeToLiveSeconds: This is the number of seconds the item has lived since cache. The default value creation of La is 0 and the item will live forever.
memoryStoreEvictionPolicy loot policy: LRU - Least recently used, less frequently used FIFO - First in, First out, oldest element by creation date.
diskExpiryThreadIntervalSeconds: The foreclosure process controls the number of seconds between two runs.
diskPersistent: Allows objects stored on disk to recover objects between two games of a virtual machine.
overflowToDisk: The maximum storage element that determines whether an object can be stored on disk

Summarize with a simple mathematical formula: expirationTime = Math.min((creationTime + timeToLive),(mostRecentTime + timeToIdle))

conclusion

This article is about spring cache code detail all content, I hope to help you. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!


Related articles: