【SpringBoot】14 缓存(cache)

发布于:2024-10-17 ⋅ 阅读:(12) ⋅ 点赞:(0)

介绍

Spring 框架支持透明地向应用程序添加缓存对缓存进行管理,其管理缓存的核心是将缓存应用于操作数据的方法(包括增删查改等),从而减少操作数据的执行次数(主要是查询,直接从缓存中读取数据),同时不会对程序本身造成任何干扰。
SpringBoot 继承了 Spring 框架的缓存管理功能,通过使用 @EnableCaching 注解开启基于注解的缓存支持,SpringBoot 就可以启动缓存管理的自动化配置。
@EnableCaching:通常配置在项目启动类,表示开启缓存功能。
@Cacheable:⽤于对方法的查询结果进行缓存存储,当存在缓存时,直接使用缓存结果,不存在缓存时,进行方法查询,将结果存入缓存。
@CachePut:表示将返回结果更新到缓存中。
@CacheEvict:表示删除缓存数据。

代码实现

第一步:添加依赖

pom.xml

<!--  缓存    -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

第二步:在启动类上添加 @EnableCaching 注解

SystemApplication.java

@EnableCaching
@SpringBootApplication
@MapperScan("com.lm.system.mapper")
public class SystemApplication extends SpringBootServletInitializer {}

第三步:在业务类上添加 @CacheConfig 直接,在业务方法上添加 @Cacheable 注解。

@Service
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {

     @Override
     @Cacheable
     public List<User> queryAllUser() {
         return userMapper.queryAllUser();
     }

}

效果图

第一次查询访问了数据库。
在这里插入图片描述
第二次查询访问了缓存(没有打印具体执行的SQL)。
在这里插入图片描述

参考资料

Spring Boot 2.x基础教程:进程内缓存的使用与Cache注解详解【https://www.didispace.com/spring-boot-2/5-1-caching.html】


网站公告

今日签到

点亮在社区的每一天
去签到