1.在pom.xml文件添加ehcache依赖
<!-- Spring Boot 缓存支持启动器 --> <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.在src/main/resources/ 下创建 Ehcache 的配置文件ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <!--defaultCache:echcache 的默认缓存策略 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </defaultCache> <!-- 自定义缓存策略 name的值随便起,后面用得上--> <cache name="UserEncache" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </cache> </ehcache>3.为了springboot能读取到xml文件,需要配置application.properties 文件
spring.cache.ehcache.cofnig=ehcache.xml4.配置信息弄之后,开始为类和方法添加注解
4.1启动类添加注解,开启缓存机制
@EnableCaching4.2对于查询的方法做缓存处理,对当前查询的对象做缓存处理,xx就是刚才xml配置的自定义名称,而且这个UserEncache是一个实体类。(注:在service层进行操作)
附UserEncache实体类表(这里使用的是JPA):
@Entity @Table(name="t_user") public class UserEncache implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="") private Integer id; @Column(name="name") private String name; @Column(name="age") private Integer age; @Column(name="address") private String address; //省略get,set,toString方法(自己右键生成就好) }在service层的注解
@Cacheable(value="UserEncache")5.编写测试代码 注:App是启动类 xxx.size(); 是查询结果有几条
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=App.class) public class ServiceTest { @Test public void testFindAll(){ //第一次查询 System.out.println(this.userEncacheServiceImpl.findUserAll().size()); //第二次查询 System.out.println(this.userEncacheServiceImpl.findUserAll().size()); } }5.1测试时结果 如果看见只有一条查询语句,那么就是使用缓存了,把结果缓存起来,下次再查询时就从缓存中获取。
附: 未使用缓存前的结果,代码一样,只是service层方法不添加 缓存注解@Cacheable(value="UserEncache")
测试结果 可见执行了两次HQL