SpringBoot中整合Ehcache缓存
为什么使用缓存?
问题:项目中查询的操作是最多的,很多查询都是重复的,但是频繁对数据库进行操作肯定会对数据库造成很大的压力,而且关系型数据库性能本身不是特别好,查询效率并不高。
解决方案:在项目当中做缓存机制,将重复的查询放到缓存中,直接从缓存中获取。
有很多种缓存的框架就不一一介绍的,该文章主要是了解如何在SpringBoot中使用Ehcache缓存框架。
浅谈Ehcache
Ehcahe是一个Java的进程内缓存框架,提供内存,磁盘文件存储,以及分布式存储方式等多种灵活的cache管理方案,Ehcache是Hibernate中默认使用的CaCheProvider,Hibernate就是使用Ehcache来使用二级缓存的。
在Spring中使用Ehcache时
主要是配置Ehcache缓存管理器(EhcacheManager),将其注入到Spring缓存管理器(CacheManager),Spring平台缓存管理器再注入到Spring缓存注解驱动。业务中只需要使用代码进行缓存。
整合Ehcache缓存中主要使用到的两个注解:
@Cacheable与@CacheEvict
@Cacheable作用:将方法的返回值添加到Ehcache中做缓存。
Value属性:指定ehcache配置文件中的缓存策略。如果没给定Value,则使用默认的缓存策略
key属性:给缓存中的值起个名称,在查询时如果有名称相同的,则从已知缓存中将数据返回。
@CacheEvict作用:清除缓存。
Ehcache默认的缓存中使用的策略介绍:
maxElementsInMemory:最大的缓存对象数量
eternal:是否持久化
timeToIdleSeconds:对象空闲时间,超过该时间没被访问则删除
timeToLiveSeconds:对象存活时间。
maxElementsOnDisk:磁盘上缓存的元素的最大数量
diskExpiryThreadIntervalSeconds:对象检测线程运行时间间隔。
memoryStoreEvictionPolicy:内存中数据超过内存限制,则向磁盘缓存。默认:LRU(最近最少使用),FIFO(先进先出),LFU(最少使用)
pom.xml的依赖项
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 测试的jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- springboot整合jpa需要的依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- druid数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!-- mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>