English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
EhCache is an open-source cache based on Java for improving performance. The current version of Ehcache is 3 . It provides JSR-107 implementation of the cache manager. We can use it directly.
Itfast,lightweight, scalableandflexible. It allows us to performserializableandobject It provides such as LRU, LFU, FIFO, etc.cache eviction policy. It stores the cache inMemoryandDisk(SSD). It depends on SLF4J for logging. It has been fully implemented JSR-107 and Jcache It supports access through JGroups or JMS and RMI for distributed caching. It usesFluent query languagefor distributed search.
The cache uses multiple access modes. EhCache uses the following modes:
Cache-aside Cache-as-SoR (system-of-record) Read-through Write-through Write-behind
In Backup cacheIn the pattern, first of all, the application queries the cache. If data is found, it will return the data directly. In the opposite case, it retrieves the data from SoR, stores it in the cache, and then returns it.
cache-as-SoR mode represents the read and write operations of SoR to the cache. It reduces the responsibility of the application. It uses a combination of read and write modes, including Direct read, direct write,and post-write. It reduces the difficulty of the application. It allows the cache to solve the thunder problem
Read-throughmode and also replicates the cache-reserving mode when reading data from the cache. The difference between read mode and cache reservation is that the read mode implements CacheEntryFactory interface. It guides the cache on how to read objects from the cache. It is best to wrap the EhCache instance as SelfPopulatingCache instance.
Write-throughmode can also replicate the backup cache mode when writing data to the cache. The difference between direct write mode and backup cache mode is that the direct write mode implements CacheWriter interface. It configures the cache for direct write and post-write modes. It writes data to SoR in the same execution thread.
Write-behindmode, different from the other three modes. In configurable delayafter which it will modify the cache entry. The delay may be in seconds, minutes, a day, a week,or for a long time. At the same time, it also queues the data for writing later in the same execution thread.
Data writing in post-write mode occurs outside the transaction scope. This means it creates a new transaction to submit data different from the main transaction in SoR.
EhCache allows us to use various data storage areas, such as heap, disk, and cluster. We can configure a multi-storage cache (using multiple storage areas). It can be scheduled as layer.
These layers are organized in order. The lowest layer is authorization layer, another layer is cache layer. Also known as nearer or near cache. The cache layer can have multiple storage areas. The hottest data is retained in the cache layer because it is faster than the authorization layer. Compared to the cache layer, other data is retained in the authorization layer, slower but richer.
The data storage types supported by EhCache are Four:
On-Heap Store Off-Heap Store Disk Store Clustered Store
It stores cache entries in the Java heap memory. It shares storage with the Java application. This is fast because it uses the heap, but the storage space is limited. The garbage collector will also scan the heap storage.
It uses the main memory (RAM) to store cache entries. The garbage collector does not scan it. It is slower than heap storage because the cache entries are moved to heap storage before use. Its size is limited.
It uses the disk to store cache entries. It is much slower than storage based on RAM (above and below). If the disk storage mode is used, it is best to use a dedicated disk.
Clustered Store
It stores cache entries on the remote server. It is slower than off-heap storage. It may have a failover server that provides high availability.
The diagram above shows An application may have multiple cache managers. Many caches can be handled by a cache manager. Caches can use multiple layers to store cache entries.
Configure EhCache EhCache jar placed on the classpath. Configure xml and place it on the classpath. Create a reference cache.
In the following examples, we will configure EhCache in the application.
Steps1: Open Spring Initializr https://start.spring.io/.
Steps2: Select Spring Boot version 2.3.0 M2 .
Steps3: Provide GroupName. We provide the group name com.w3codebox.
Steps4: Provide Artifact.We provide Artifact spring-boot-ehcache-example.
Steps5: Add Spring Web Dependencies.
Steps6: Click Generate (Generate) button. When we click the "Generate" button, it will package all the specifications related to the application into a Jar the files from the jar and download them to the local system.
Steps7: Extract jar files.
Steps8: Copy the folder and paste it into the STS workspace.
the9step: ImportProject.
File->Import->Existing Maven project->Next->Browse->Select folder spring-boot-ehcache-example->Select folder->Complete
.
Steps10: It takes time to import the project from the Maven repository https://mvnrepository.com/and paste it into in the pom.xmlFile.
spring-boot-starter-cache ehcache 3 cache API.
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.M2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.w3codebox</groupId> <artifactId>spring-boot-ehcache-example</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-ehcache-example</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </pluginRepository> </pluginRepositories> </project>
Now, we need to configure ehcache.xml File.
Steps11: Open application.properties File, and use the following properties to configure EhCache.
application.properties
#Configure ehcache.xml spring.cache.jcache.config=classpath:ehcache.xml
Steps12: Open SpringBootEhcacheExampleApplication.java File, and use annotations @EnableCaching Enable caching.
SpringBootEhcacheExampleApplication.java
package com.w3codebox; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication //Enable cache management functionality @EnableCaching public class SpringBootEhcacheExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootEhcacheExampleApplication.class, args); } }
package com.w3codebox; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Configuration; @Configuration //enable caching @EnableCaching public class CacheConfig { }
Steps13: Create a class. We have already created a package com.w3codebox Created a name of The class Student. In the class, perform the following operations:
Create five variablesid, name, gender,and generateUse Constructor
Right-click on the file->source->Use field to generate builder->Select all->生成 generateGetters and Setters.
Right-click on the file->source->Generate Getter and Setter->Select all->生成 generate toString() Right-click on the file->source->generate toString()->生成
完成上述所有步骤后,类如下所示。
>Generated
package com.w3codebox; After completing all the above steps, the class looks like this. { Student.java public class Student private int id; private String name; private String gender; { private String city; return id; return name; return gender; return city; } public Student(int id, String name, String gender, String city) { super(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getCity() { return city; } public void setCity(String city) this.city = city; { @Override + id + public String toString() + return "Student [id=" + ", name=" + name + ", gender=" + gender + ", city=" } }
Steps14: city "]";Create a class to manage students Service Class. We have created a service named
StudentManager service class. In this course, we have completed the following operations: Using annotations @Service annotated class. Create HashMap instance. in the static block, we have added student data to the map. Through the use of annotationsCacheablekeys, we have defined the cache name where all data will be stored. We have already added student data in the annotation's id . Caching is defined according to id to search for students. We have created a method getStudentById()This method parses the id into a parameter. It returns the student's id .
StudentManager.java
StudentManager.java package com.w3codebox; import java.util.HashMap; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class StudentManager { static HashMap<Integer, Student> student = new HashMap<>(); static { student.put(1, new Student(10, 0, "Alex", "Male", "Berlin"); student.put(2, new Student(101, "Tony", "Male", "Maxico"); student.put(3, new Student(102, "Andrew", "Male", "Chicago"); student.put(4, new Student(103, "Alexa", "Female", "Brussels"); student.put(5, new Student(104, "Maria", "Female", "Houston"); } @Cacheable(cacheNames="demoCache", key="#id")public Student getStudentById(Integer id) { System.out.println("Fetching student data from cache"); return student.get(id); } }
Now, we need to create ehcache.xml file. It contains information related to the cache, such as the name of the cache, the number of elements in memory, and the real-time data survival time in the cache.
the15step: In src/main/resources in the ehcache.xml is the configuration file.
ehcahe.xml
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance xmlns='http://www.ehcache.org/v3" xmlns:jsr107='http://www.ehcache.org/v3/jsr107"> <ehcache> <diskStore path="java.io.tmpdir" /> <defaultCache maxElementsInMemory="2000" eternal="true" overflowToDisk="false" timeToLiveSeconds="1200" /> <cache name="demoCache" maxElementsInMemory="2000" eternal="false" overflowToDisk="false" timeToLiveSeconds="10000" /> </ehcache> </config>
Now, we have created all the necessary files. After creating all the files, the project directory is as follows:
Let's run the application.
Steps16: Open SpringBootEhcacheExampleApplication.java file, and as a Java application.
It shows the following output:
Getting Students from Cache [id=100, name=Alex, gender=Male, city=Berlin] [id=101, name=Tony, gender=Male, city=Mexico] [id=102, name=Andrew, gender=Male, city=Chicago] [id=103, name=Alexa, gender=Female, city=Brussels] [id=104, name=Maria, gender=Female, city=Houston]