The main research in this article is about spring cache related content, as follows.
This article was roughly modified based on Google Translation. Since I don’t know what the original text is, it may lead to errors and inaccuracies in the translation, but the general direction feels quite good, so I sorted it out here, hoping it will be helpful.
Caching has always been a big need for both to improve application performance and reduce its workload. Furthermore, its usefulness is particularly evident today, which can be made to handle thousands of visitors on the architecture of web applications, cache management orthogonal to the application's business logic and for this reason should have minimal impact on the development of the application itself. Starting from version 3.1, Spring provides a cache management API, similar to declarative transaction management. The abstract interface of cache, using different cache solutions in a unified way, has the least impact on the code.
Spring uses Java methods to request a method for the first time for a combination with parameters, and spring stores the return value in the cache. Therefore, the next request will be to use the value from the cache directly without having to call a possible costly method. Everything is applied transparently without affecting the method called.
In this post, we will see two different cache storage implementations from Spring.
- ConcurrentHashMap for Java
- Ehcache
accomplish
The integration of spring and cache is simple and transparent. The method that needs cache is annotated by @Cacheable annotation
@Cacheable(value= "dataCache") public Reponse getDatas(Long param1, String param2){ }
dataCache is the name of the associated cache. When this method is called for the first time, the method executes and stores the execution result in the result set with the secret key hashed out of <parameter 1 and parameter 2> as the result. When the same parameter is called again, this method does not need to be executed again.
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 is executed, and if there is a hit, the relevant value will be returned.
Generate cache keys
The proportion of basic algorithms of a cache manager is relatively small. The cache can be regarded as a memory area in which the objects stored are mapped by a unique key. The process of object search is as follows:
1. Calculate the key (use hash method to obtain hashcode)
2. Find objects based on key value
3. If the object is found, return the result
4. If it cannot be found, the key that is actually associated with the object will be calculated and the object will be stored in the corresponding location.
spring uses a simple hash, which generates keys based on passed method parameters.
Custom cache
The target method cannot simply generate unnecessary keys based on parameters, but only some simple cases are generated based on parameters.
@Cacheable(value= "dataCache") public Reponse getDatas(Long param1, String param2, boolean param3){ }
@Cacheable allows developers to specify the way key generation is generated by themselves. You can use spel expressions to do this.
@Cacheable(value= "dataCache", key="#param2") public Reponse getDatas(Long param1, String param2, boolean param3){ }
In this case above, the parameter of the cached key is only Parma2
spring also allows nested properties
@Cacheable(value="dataCache", key=#") public Reponse getDatas(Long param1, Data param2, boolean param3){}
This situation is the secret key calculated based on the name attribute of Parma2
Conditional cache
There is a cache that may not be suitable for the cache in the used case, but in some cases, cache is required. When cached, cache is processed based on the true or false calculated by the SPEL expression, and if the condition is true, cache is performed.
@Cacheable(value= "dataCache", key="#param2", condition="#<64") public Reponse getDatas(Long param1, String param2, boolean param3){ }
In this case, cache will only be performed if the length of the second parameter is less than 64
@CacheEvict annotation
Spring's cache can not only cache data but also clear a cache storage. This process is used to remove outdated data or unused cached data. Annotation @CacheEvict defines methods for performing cache emptiation, these are triggers for deleting data in cache.
@CacheEvict(value= "dataCache") public void reloadData(){ }
This option is very necessary, and this method will be used when a cached data needs to be cleared.
Enable cache
To enable cache support for a spring project, we need to add cache comments to the namespace.
<beans xmlns="/schema/beans" xmlns:cache="/schema/cache" xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:context="/schema/context" xsi:schemaLocation="/schema/beans /schema/beans/spring-beans-3. /schema/cache /schema/cache/ /schema/context"> <cache:annotation-driven />
Delete annotation can disable cache, or enable cache usage in our configuration class
@Configuration @EnableCaching public class AppConfig { }
Technical limitations
The parameters of the object pass method must have their own hashcode method in order to calculate the secret key.
As an object passed and returned as a parameter, it should be serializable
Implement selection
Spring provides two basic implementations:
- java's concurrentHashMap
- Ehcache
When using them, you only need to declare the appropriate CacheManger and manager entity
ConcurrentHashMap using java
<bean class=""> <span style="white-space:pre"> </span><property name="caches"> <span style="white-space:pre"> </span><set> <span style="white-space:pre"> </span><bean class="" name="default"/> <span style="white-space:pre"> </span><bean class="" name="dataCache"/> <span style="white-space:pre"> </span></set> <span style="white-space:pre"> </span></property> </bean>
Each Manger needs a name, which is recognized by comments. One can manage multiple SimpleCacheMangers by a Manger, and this implementation is basically unnecessary.
Implement Ehcache
Statement of CacheManger
bean class=""> <property name="cacheManager" ref="ehcache"/> </bean> <bean class=""> <property name="configLocation" value="classpath:"/> <property name="shared" value="true"/> </bean>
In the file is the application cache parameter file:
<ehcache xsi:noNamespaceSchemaLocation="" updateCheck="true" monitoring="autodetect" dynamicConfig="true" maxBytesLocalHeap="150M"> <diskStore path=""/> <defaultCache eternal="false" maxElementsInMemory="100" overflowToDisk="false"/> <cache name="dataCache" eternal="false" timeToIdleSeconds="300" maxBytesLocalHeap="30M" timeToLiveSeconds="300" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/> </ehcache>
Using ehcache, we can define multiple cache different parameters in a very simple way
Name: cached identifier
maxBytesLocalHeap: Defines the number of bytes that the cache can use for the virtual machine. If a CacheManager maxBytesLocalHeap has been set, the determined size of the cache will be subtracted by the CacheManager. Other cache shared breaks. The value of this property is data <number> K | K | M | M | G | G stands for kilobytes (K | K), megabytes (M | M) or gigabytes (G | G).
Eternity: Defines whether an element is eternal. If this is the case, the timeout will be ignored and the project is never expired.
timeToIdleSeconds: This is the number of seconds, the item has remained still since its last default value was 0.
timeToLiveSeconds: This is the number of seconds the project has lived since the default value is created as 0, and the project will be alive forever.
memoryStoreEvictionPolicy Plunder Policy: LRU - Least recently used, infrequently used FIFO - First-in, oldest element by creation date.
diskExpiryThreadIntervalSeconds: The foreclosure process controls the number of seconds between two runs.
diskPersistent: Allows the object to recover objects between two matches of a virtual machine stored on disk.
overflowToDisk: Determines whether an object can be stored on disk to achieve the maximum storage element.
To summarize it, use a simple mathematical formula:expirationTime = ((creationTime + timeToLive),(mostRecentTime + timeToIdle))
Summarize
The above is all the detailed explanation of spring cache code in this article, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!