SpringBoot implements data caching function at the annotation level, based on Spring's AOP technology. All cache configurations are only configured at the annotation level, like declarative transactions.
Spring defines CacheManager and Cache interfaces to unify different caching technologies. Among them, CacheManager is an abstract interface for various caching technologies provided by Spring. The Cache interface contains various cache operations.
CacheManger
For different cache technologies, different cacheManagers need to be implemented. Spring defines the following cacheManger implementation.
| CacheManger | describe |
|---|---|
| SimpleCacheManager | Use simple collection to store caches, mainly for testing |
| ConcurrentMapCacheManager | Use ConcurrentMap as cache technology (default) |
| NoOpCacheManager | For testing |
| EhCacheCacheManager | EhCache is used as a cache technology, and used to be often used when hibernate |
| GuavaCacheManager | GuavaCache using google guava as caching technology |
| HazelcastCacheManager | Using Hazelcast as a caching technique |
| JCacheCacheManager | Implementation using JCache standard as caching techniques such as Apache Commons JCS |
| RedisCacheManager | Using Redis as a caching technology |
The regular SpringBoot has automatically configured EhCache, Collection, Guava, ConcurrentMap and other caches for us, and the ConcurrentMapCacheManager is used by default. SpringBoot's application.properties configuration file, configured using the properties of the spring.cache prefix.
Application Configuration
spring.cache.type=#Cached technical type spring.cache.cache-names=The name of the application starts to create the cache, spring.cache.ehcache.config=ehcache configuration file location spring.cache.infinispan.config=infinispan configuration file location spring.cache.jcache.config=jcache configuration file location spring.cache.jcache.provider=Specify the implementation class of jcache when multiple jcache implementation classes
Entry class configuration
Add annotation @EnableCaching
Cache annotation
| annotation | describe |
|---|---|
| @Cacheable | Before calling a method, you should first look for the return value of the method in the cache. If this value can be found, the cached value will be returned. Otherwise, this method will be called and the return value will be placed in the cache. |
| @CachePut | Put the return value of the method into the cache. The cache is not checked before the method is called, and the method will always be called. |
| @CacheEvict | Clear one or more entries in the cache. |
| @Caching | Grouped annotations can be applied at the same time multiple other cache annotations. |
Manually use EhCache
During the actual development process, there is a situation where there is no use of annotations and you need to add cache yourself. Let’s take Ehcache as an example and briefly write down the configuration process.
1. Add dependencies
Introduce springboot-cache and ehcache. It should be noted that EhCache does not require version configuration, and the root pom of SpringBoot has been integrated.
<!-- Cache--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- ehcache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency>
2. Entry class configuration
Add annotation @EnableCaching
@SpringBootApplication@EnableCachingpublic class DemoApplication {} 3. EhCache configuration
In the src/main/resources directory, add the ehcache.xml file, see the content at the end of the article.
4. Application.application configuration
# Configure ehcache cache spring.cache.type=ehcache# Specify the path of ehcache configuration file spring.cache.ehcache.config=classpath:/ehcache.xml
5. Use Cache
Inject SpringBoot's automatically configured bean, org.springframework.cache.CacheManager.
A simple test class:
package com.bbf.frame.test;import com.bbf.frame.Application;import org.apache.commons.lang3.StringUtils;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.cache.Cache;import org.springframework.cache.CacheManager;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import javax.annotation.Resource;@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)public class TestCache { @Resource private CacheManager cacheManager; @Test public void cacheTest() { // Show all Cache spaces System.out.println(StringUtils.join(cacheManager.getCacheNames(), ",")); Cache cache = cacheManager.getCache("userCache"); cache.put("key", "123"); System.out.println("Cache Success"); String res = cache.get("key", String.class); System.out.println(res); }} Appendix EhCache.xml
<?xml version="1.0" encoding="UTF-8"?><ehcache xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation = "http://ehcache.org/ehcache.xsd" updateCheck = "false"> <!-- Specify a file directory. When EHCache writes data to the hard disk, the data will be written to this file directory --> <diskStore path = "java.io.tmpdir"/> <!-- Default Management Policy --> <defaultCache eternal = "false" maxElementsInMemory = "10000" overflowToDisk = "true" diskPersistent = "false" timeToIdleSeconds = "120" timeToLiveSeconds = "120" diskExpiryThreadIntervalSeconds = "120" memoryStoreEvictionPolicy = "LRU"/> <!-- This cache can survive up to timeToLiveSeconds seconds. If the period exceeds timeToIdleSeconds seconds and the cache is invalidated --> <cache name = "userCache" eternal = "false" maxElementsInMemory = "100" overflowToDisk = "false" diskPersistent = "false" timeToIdleSeconds = "120" timeToLiveSeconds = "180" memoryStoreEvictionPolicy = "LRU"/> <!-- maxElementsInMemory The maximum number of cached objects in memory, look at your heap size to do it --> <!-- eternal: true means that the object will never expire. At this time, the timeToIdleSeconds and timeToLiveSeconds properties will be ignored, and the default is false --> <!-- maxElementsOnDisk: The maximum number of cached objects in the hard disk, if 0 means infinity --> <!-- overflowToDisk: true means that when the number of objects cached in the memory reaches the maxElementsInMemory limit, the overflowed objects will be written to the hard disk cache. Note: If the cached object is to be written to the hard disk, the object must implement the Serializable interface. --> <!-- diskSpoolBufferSizeMB: Disk cache size, default is 30MB. Each cache should have its own cache area. --> <!-- diskPersistent: Whether to cache virtual machine restart data --> <!-- diskExpiryThreadIntervalSeconds: The disk failure thread run time interval, default is 120 seconds --> <!-- timeToIdleSeconds: Sets the maximum time to allow the object to be idle, in seconds. When the object has been accessed for the last time, if the timeToIdleSeconds property value exceeds the timeToIdleSeconds property value, the object will expire and EHCache will clear it from the cache. This property is only valid if the eternal property is false. If the value of this property is 0, it means that the object can be idle indefinitely --> <!-- timeToLiveSeconds: Sets the maximum time the object allows to exist in the cache, in seconds. When the object has been stored in the cache, if the time in the cache exceeds the timeToLiveSeconds property value, the object will expire and EHCache will clear it from the cache. This property is only valid if the eternal property is false. If the property value is 0, it means that the object can exist in the cache indefinitely. timeToLiveSeconds must be greater than the timeToIdleSeconds property to make sense --> <!-- memoryStoreEvictionPolicy: When the maxElementsInMemory limit is reached, Ehcache will clean up memory according to the specified policy. Optional policies are: LRU (latest recently used, default policy), FIFO (first in, first out), and LFU (minimum number of visits). --></ehcache>
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.