springboot 整合缓存(Ehcache或者reids)
这里介绍Spring Boot结合JPA,MySQL和Ehcache实现缓存功能,提高程序访问效率。
一、Maven依赖
<!-- caching -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
二、程序的启动类加上 @EnableCaching
3、application.yml和ehcache.xml配置文件
application.yml
#使用ehcache缓存配置
spring:
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<cache name="sysCache"
maxElementsInMemory="100000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="true"
memoryStoreEvictionPolicy="LRU"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
4、使用
注意:
1)@CacheConfig(cacheNames = {“lemonCache”})设置了ehcache的名称,这个名称就是ehcache.xml内的名称; (可以不指定,应为在yml 中已经制定了)
2)@Cacheable:应用到读取数据的方法上,即可缓存的方法,如查找方法:先从缓存中读取,如果没有再调 用方法获取数据,然后把数据添加到缓存中,适用于查找;
3)@CachePut:主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用。适用于更新和插入;
4)@CacheEvict:主要针对方法配置,能够根据一定的条件对缓存进行清空。适用于删除。
整合reids https://blog.csdn.net/plei_yue/article/details/79362372
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构