集成 Ehcache 实现本地缓存切换
# 集成 Ehcache 实现本地缓存切换详细步骤
在一些项目中,由于规模较小,不需要使用 Redis 作为缓存服务,集成 Ehcache 可以实现将缓存数据存储在本地,从而简化项目部署。
# 1. 添加 spring-cache
和 ehcache
依赖
首先,需要在 pom.xml
文件中添加 spring-cache
和 ehcache
的依赖,以启用 Spring 的缓存功能并支持 Ehcache。
<!-- Spring Cache 依赖配置 -->
<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
3
4
5
6
7
8
9
10
11
如果项目中有多个模块,需要在 ruoyi-common/pom.xml
中重复添加这些依赖。
# 2. 配置 application.yml
文件
在 ruoyi-admin
项目的 application.yml
文件中添加缓存配置,指定缓存类型为 ehcache
,并配置相关参数。
spring:
cache:
# 指定缓存类型:ehcache 或 redis
type: ehcache
ehcache:
config: classpath:ehcache.xml # 指定 Ehcache 配置文件的路径
redis:
time-to-live: 86400000 # 缓存的存活时间(ms)
use-key-prefix: true # 是否使用缓存前缀
cache-null-values: true # 是否缓存空值,防止缓存穿透
2
3
4
5
6
7
8
9
10
在此配置中,type
属性控制使用哪种缓存类型。如果需要切换为 Redis,只需将 type: ehcache
改为 type: redis
。
# 3. 创建 Ehcache 配置文件
在 src/main/resources
目录下创建 ehcache.xml
文件,用于配置 Ehcache 缓存策略。
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<cache name="defaultCache"
maxEntriesLocalHeap="1000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
diskSpoolBufferSizeMB="20"
maxEntriesLocalDisk="10000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
statistics="true">
<persistence strategy="localTempSwap"/>
</cache>
<!-- 可以根据需要添加更多的缓存配置 -->
</ehcache>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
该文件配置了一个名为 defaultCache
的缓存区域,设置了最大堆内存条目数、闲置时间、存活时间等参数。根据需求,可以在文件中添加更多的缓存配置。
# 4. 插件相关包和代码实现
为了简化配置,插件相关的代码和配置已封装在 ruoyi-vue/集成ehcache实现本地缓存切换.zip
中。请下载并解压,按照提示将文件覆盖到项目中。
下载链接: 集成 Ehcache 实现本地缓存切换 (opens new window)
提取码: mjs7
# 5. 测试验证
完成上述配置后,关闭 Redis 服务,启动 RuoYi 项目。通过登录和其他操作验证本地缓存的效果。如果需要切换回 Redis,只需在 application.yml
中将缓存类型从 ehcache
切换为 redis
,然后重新启动项目。
# 注意事项
- 确保
ehcache.xml
文件路径正确,并且配置文件内容符合实际项目需求。 - 切换缓存类型时,需要重新启动应用程序以使配置生效。
通过以上步骤,你可以成功集成 Ehcache 实现本地缓存切换,同时保留使用 Redis 作为缓存的能力。这一配置在保证灵活性的同时,也提供了简洁的项目部署方案。