前言
日常开发中,缓存是解决数据库压力的一种方案,通常用于频繁查询的数据,例如新闻中的热点新闻,本文记录Spring Boot中使用cache缓存。
工程结构

代码编写
pom引入依赖,引入cache缓存,数据库使用mysql,ORM框架用jpa
<!--添加springdata-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>
<!--添加springdata-jpa依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--添加MySQL驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
配置文件
server.port=10010
spring.application.name=springboot-cache
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:/ehcache.xml
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir"/>
<!-- maxEntriesLocalHeap:堆内存中最大缓存对象数,0没有限制 -->

本文介绍了如何在Spring Boot项目中使用缓存来优化数据库查询,通过添加相关依赖、配置及代码注解实现缓存CRUD操作。详细展示了save、get、update和delete操作如何与缓存配合,确保数据的一致性。同时,讨论了缓存有效期的设置以及在实际场景中的应用。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



