spring boot integrates ehcache to implement caching mechanisms

  • 2020-12-26 05:44:58
  • OfStack

EhCache is a pure Java in-process caching framework, with the characteristics of fast, lean and so on, is the default CacheProvider in Hibernate.

ehcache offers a variety of caching strategies, mainly at memory and disk levels, so you don't have to worry about capacity.

spring-boot is a fast integration framework designed to simplify the initial setup and development process for new Spring applications. The framework is configured in a way that eliminates the need for developers to define boilerplate configurations.

Since spring-ES16en does not require any boilerplate configuration files, the integration of ES17en-ES18en with 1 other frameworks will be slightly different.

1. spring-boot is a framework for jar packages managed through maven. The dependencies required to integrate ehcache are as follows


 <dependency>
 <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
   <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
   <version>2.8.3</version>
</dependency> 

Details of the ES29en. xml file are shown below


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.lclc.boot</groupId>
 <artifactId>boot-cache</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <!-- Inherit defaults from Spring Boot -->
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.1.3.RELEASE</version>
 </parent>
 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
  </dependency>
  <dependency>
   <groupId>com.google.guava</groupId>
   <artifactId>guava</artifactId>
   <version>17.0</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
  </dependency>
  <dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache</artifactId>
   <version>2.8.3</version>
  </dependency>
 </dependencies>
 <dependencyManagement>
  <dependencies>
  </dependencies>
 </dependencyManagement>
 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>
 <repositories>
  <repository>
   <id>spring-snapshots</id>
   <url>http://repo.spring.io/snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </repository>
  <repository>
   <id>spring-milestones</id>
   <url>http://repo.spring.io/milestone</url>
  </repository>
 </repositories>
 <pluginRepositories>
  <pluginRepository>
   <id>spring-snapshots</id>
   <url>http://repo.spring.io/snapshot</url>
  </pluginRepository>
  <pluginRepository>
   <id>spring-milestones</id>
   <url>http://repo.spring.io/milestone</url>
  </pluginRepository>
 </pluginRepositories>
</project>

2. Using ehcache, we need 1 ehcache.xml to define 1 cache attribute.


<?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">
   <diskStore path="java.io.tmpdir/Tmp_EhCache" />
   <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
 timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" />
   <cache name="demo" eternal="false" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false"
 timeToIdleSeconds="0" timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" />
</ehcache>

Explain the tag in the xml file.

(1).diskStore: For the cache path, ehcache is divided into memory and disk levels. This property defines the cache location of the disk. The parameters are explained as follows:

user. home user home directory
user. dir user's current working directory
java. io. tmpdir has the default temporary file path

(2).defaultCache: the default caching policy. When ehcache cannot find the defined cache, it uses this caching policy. I can only define one.

(3).cache: Self-defined caching policy, which is a customized caching policy. The parameters are explained as follows:

Attributes of the cache element:

name: Cache name
maxElementsInMemory: Maximum number of cached objects in memory
maxElementsOnDisk: Maximum number of cached objects on hard disk. If 0 is infinite
eternal: true indicates that the object will never expire, and the timeToIdleSeconds and timeToLiveSeconds attributes are ignored at this point, default to false
overflowToDisk: true means that when the number of objects in the memory cache reaches the maxElementsInMemory limit, the overflow 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 to 30MB. Each Cache should have its own 1 cache area.
diskPersistent: Whether to cache virtual machine restart period data
diskExpiryThreadIntervalSeconds: Disk invalidated threads run time interval, default is 120 seconds
timeToIdleSeconds: Sets the maximum amount of time in seconds that an object is allowed to remain idle. If an object has been idle for more than the timeToIdleSeconds attribute value since its last access, the object will expire and EHCache will clear it from the cache. The eternal attribute is valid only if it is false. If the value of this property is 0, then the object can remain idle indefinitely
timeToLiveSeconds: Sets the maximum amount of time an object is allowed to exist in the cache, in seconds. When an object has been in the cache since it was placed, if it has been in the cache longer than the value of the timeToLiveSeconds attribute, the object will expire and EHCache will clear it from the cache. The eternal attribute is valid only if it is false. If the value of this property is 0, then the object can remain in the cache indefinitely. timeToLiveSeconds must be greater than timeToIdleSeconds to be meaningful
memoryStoreEvictionPolicy: When the maxElementsInMemory limit is reached, Ehcache will clear memory according to the specified policy. The optional policies are: LRU (least recently used, default), FIFO (first in first out), LFU (least visited).

3. Expose ehcache's manager to spring's context container,


@Configuration
//  The annotation starts the cache 
@EnableCaching
public class CacheConfiguration {
 /*
  * ehcache  The primary manager 
  */
 @Bean(name = "appEhCacheCacheManager")
 public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
  return new EhCacheCacheManager (bean.getObject ());
 }

 /*
  *  According to the shared Setting whether or not ,Spring Respectively by CacheManager.create() or new CacheManager() Way to create 1 a ehcache base .
  */
 @Bean
 public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
  EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean ();
  cacheManagerFactoryBean.setConfigLocation (new ClassPathResource ("conf/ehcache-app.xml"));
  cacheManagerFactoryBean.setShared (true);
  return cacheManagerFactoryBean;
 }
}

Configuration: Annotation for spring-ES124en, mainly marked as a configuration class, priority scanning.

Bean: Add bean to the spring container.

At this point, all the configuration is done and the integration framework through spring-boot is as simple as that.

4. Use ehcache

ehcache is mainly used through spring's caching mechanism. Above, spring's caching mechanism is implemented using ehcache, so the spring caching mechanism is completely used in the use of aspects.
There are several notes:

Cacheable: Responsible for adding the return value of the method to the cache, argument 3
CacheEvict: responsible for clearing the cache, parameter 4

Parameter interpretation:

value: Cache location name, cannot be empty, if EHCache is used, it is name of cache declared in ES156en.xml
key: The cached key is empty by default, indicating that the parameter type and parameter value of the method to be used are key. SpEL is supported
condition: Trigger condition, only if the condition is met, will be added to the cache, default is empty, that means all are added to the cache, SpEL is supported

allEntries: CacheEvict parameter, true means to clear all caches in value, default is false

Without further ado, code directly:


@Service
public class CacheDemoServiceImpl implements CacheDemoService {
 /**
  *  The cache key
  */
 public static final String THING_ALL_KEY = "\"thing_all\"";
 /**
  * value Property indicates which cache policy is used, and the cache policy is in ehcache.xml
  */
 public static final String DEMO_CACHE_NAME = "demo";
 @CacheEvict(value = DEMO_CACHE_NAME,key = THING_ALL_KEY)
 @Override
 public void create(Thing thing){
  Long id = getNextId ();
  thing.setId (id);
  data.put (id, thing);
 } 
  @Cacheable(value = DEMO_CACHE_NAME,key = "#thing.getId()+'thing'")
 @Override
 public Thing findById(Long id){
  System.err.println (" No cache gone! " + id);
  return data.get (id);
 }
  @Cacheable(value = DEMO_CACHE_NAME,key = THING_ALL_KEY)
 @Override
 public List<Thing> findAll(){
  return Lists.newArrayList (data.values ());
 }
  @Override
 @CachePut(value = DEMO_CACHE_NAME,key = "#thing.getId()+'thing'")
 @CacheEvict(value = DEMO_CACHE_NAME,key = THING_ALL_KEY)
 public Thing update(Thing thing){
  System.out.println (thing);
  data.put (thing.getId (), thing);
  return thing;
 }
 @CacheEvict(value = DEMO_CACHE_NAME)
 @Override
 public void delete(Long id){
  data.remove (id);
 }
}

5. Simply annotate the service layer method to use caching, cache on find**, and clear on delete**,update**.

conclusion


Related articles: