原文: https://howtodoinjava.com/spring-boot/ehcache2-config-example/
了解如何使用 ehcache 2.x 在 spring boot 应用程序中配置缓存。 学习使用基于注解的缓存配置以及使用CacheManager手动更新缓存。
1. Maven 依赖
在此示例中,我们使用的是 Spring 运行版本1.5.13.RELEASE。 较早的 spring boot 版本支持net.sf.ehcache软件包下的ehcache 2.x。
我们需要以下依赖项来添加缓存功能。
spring-boot-starter-cache- ehcache(
net.sf.ehcache) - 缓存 API(
javax.cache)
pom.xml
<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.company</groupId><artifactId>SpringBootEhcache</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>SpringBootEhcache</name><url>http://maven.apache.org</url><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.13.RELEASE</version><relativePath /></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><skipTests>true</skipTests></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache</artifactId></dependency><dependency><groupId>javax.cache</groupId><artifactId>cache-api</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
2. ehcache.xml
Spring Boot 会自动检测classpath中是否存在ehcache.xml并对其进行配置。 在这里,我们提供缓存名称,到期时间等。
在 ehcache 文档中找到属性的完整列表。
ehcache.xml
<ehcache><diskStore path="java.io.tmpdir" /><defaultCache maxElementsInMemory="2000"eternal="true"overflowToDisk="false"timeToLiveSeconds="1200" /><cache name="employeeCache"maxElementsInMemory="2000"eternal="false"overflowToDisk="false"timeToLiveSeconds="10000" /></ehcache>
3. @EnableCaching
它启用 Spring 的注解驱动的缓存管理功能,并在调用@Cacheable注解方法时启用对拦截器的支持。
CacheConfig.java
import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Configuration;@Configuration@EnableCachingpublic class CacheConfig {}
4. @Cacheable注解
要缓存从方法调用返回的数据,我们可以在方法上使用@Cacheable注解。 使用其属性cacheNames和key来指代缓存和缓存条目的键属性。
EmployeeManager.java
import java.util.HashMap;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;@Servicepublic class EmployeeManager{static HashMap<Long, Employee> db = new HashMap<>();static {db.put(1L, new Employee(1L, "Alex", "Gussin"));db.put(2L, new Employee(2L, "Brian", "Schultz"));}@Cacheable(cacheNames="employeeCache", key="#id")public Employee getEmployeeById(Long id) {System.out.println("Getting employee from DB");return db.get(id);}}
5. CacheManager API
有时,在使用注解似乎不是完美解决方案的情况下,我们可能需要使用缓存。 在这种情况下,我们可以使用org.springframework.cache.CacheManager和org.springframework.cache.Cache抽象来访问并利用 ehcache 添加和访问缓存条目。
要使用CacheManager,我们必须首先自动装配到 spring 组件中,并使用它的getCache(name)方法来按名称获取缓存实例。
访问缓存后,我们可以使用其get()和put()方法来添加和访问缓存条目。
//1@Autowiredprivate CacheManager cacheManager;//2Cache cache = cacheManager.getCache("myCache");cache.put(3L, "Hello");String value = cache.get(3L).get();
6. Spring boot ehcache 2 示例 – 演示
我正在创建一个模型类Employee,其实例将被缓存。
Employee.java
import java.io.Serializable;public class Employee implements Serializable{private static final long serialVersionUID = 5517244812959569947L;private Long id;private String firstName;private String lastName;public Employee() {super();}public Employee(Long id, String firstName, String lastName) {super();this.id = id;this.firstName = firstName;this.lastName = lastName;}//Getters and setters@Overridepublic String toString() {return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";}}
现在在演示应用程序类中,我正在使用@Cacheable注解测试基于注解的缓存访问,并使用CacheManager进行手动缓存访问。
Application.java
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cache.Cache;import org.springframework.cache.CacheManager;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class Application {@Autowiredprivate CacheManager cacheManager;@Autowiredprivate EmployeeManager employeeManager;public static void main(String[] args) {SpringApplication.run(Application.class, args);}@Beanpublic CommandLineRunner commandLineRunner(ApplicationContext ctx) {return args -> {//This will hit the databaseSystem.out.println(employeeManager.getEmployeeById(1L));//This will hit the cache - verify the message in console outputSystem.out.println(employeeManager.getEmployeeById(1L));//Access cache instance by nameCache cache = cacheManager.getCache("employeeCache");//Add entry to cachecache.put(3L, "Hello");//Get entry from cacheSystem.out.println(cache.get(3L).get());};}}
程序输出。
Console
Getting employee from DBEmployee [id=1, firstName=Alex, lastName=Gussin]Employee [id=1, firstName=Alex, lastName=Gussin] //Fetched from cacheHello
请在评论中使用 ehcache 将有关此 spring boot 缓存示例的问题交给我。
学习愉快!
