Spring Cache

文章目录

在高并发环境下,频繁的数据库查询可能会导致性能瓶颈。使用 Redis 缓存数据可以显著减少数据库的查询次数,提高应用的响应速度和稳定性。

首先演示一下手动缓存(较为繁琐)

java 复制代码
/**
 * 根据分类id查询菜品
 *
 * @param categoryId
 * @return
 */
@GetMapping("/list")
@ApiOperation("根据分类id查询菜品")
public Result<List<DishVO>> list(Long categoryId) {

    // 构造redis中的key,规则:dish_分类id
    String key = "dish_" + categoryId;

    // 查询redis中是否存在菜品数据
    List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
    if (list != null && list.size() > 0) {
        // 如果存在,直接返回,无需查询数据库
        return Result.success(list);
    }

    Dish dish = new Dish();
    dish.setCategoryId(categoryId);
    dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品

    // 如果不存在,查询数据库,将查询到的数据放入redis中
    list = dishService.listWithFlavor(dish);
    redisTemplate.opsForValue().set(key, list);

    return Result.success(list);
}

使用Spring Cache实现缓存数据

介绍

Spring Cache 是一个框架,实现了基于注解 的缓存功能,只需简单地加一个注解,就能实现缓存功能。

常用的是Redis缓存 ,spring Cache 底层通过Redis实现缓存数据。

步骤
引入依赖

首先引入依赖(需要引入cache、redis、MySQL依赖), 在 pom.xml 文件中添加以下依赖:

cache依赖:

java 复制代码
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>  		            		       	 <version>2.7.3</version> 
</dependency>

redis依赖:

java 复制代码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

mysql依赖:

java 复制代码
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
开启缓存支持

在启动类上添加 @EnableCaching 注解以启用缓存功能:

java 复制代码
@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
配置缓存

在 application.properties 或 application.yml 中配置 Redis 缓存:

java 复制代码
# Redis 配置
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
使用缓存注解

通过在方法上使用 @Cacheable, @CachePut, 和 @CacheEvict 注解来进行缓存操作:

  • @Cacheable:缓存方法的结果
  • @CachePut:更新缓存中的数据
  • @CacheEvict:从缓存中移除数据

在spring boot 项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching开启缓存支持即可。

小结

  • 手动缓存: 使用 RedisTemplate 进行缓存操作,适用于灵活控制缓存的场景。
  • 自动缓存: 使用 Spring Cache注解简化缓存配置,适用于标准缓存需求。
相关推荐
Joy T3 小时前
Agent 确定性上下文设计:从 Prompt 参数注入到能力分层
java·开发语言·微服务·架构·prompt·agent context
m0_587383006 小时前
广州 24 小时自助健身房解决方案技术实现与实战指南
java·spring·小程序·架构·需求分析
·云扬·6 小时前
Prompt 工程与安全:从 System 设计到注入防御
java·人工智能·安全·ai·prompt
代码不停7 小时前
自动化测试(java)
java·开发语言·selenium·自动化
行百里er7 小时前
Redis 完结篇——Redis 热点问题在 Spring Boot 项目中实战
redis·后端
唠点键盘之外的8 小时前
26 向量数据库实战:从 0 搭一条能用的检索链路(pgvector + Spring AI)
数据库·人工智能·spring
高频因子挖掘机8 小时前
只取最近 60 个交易日,却每次拉全历史:量化脚本变慢的原因与改法
后端·github·api
鬼手点金9 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
孟健9 小时前
从5000亿Token到83%字节匹配:AI逆向工程与重构的工程闭环实践
后端·架构·ai编程
paopaokaka_luck10 小时前
滑雪场管理系统(AI智能助手流式对话,ECharts 运营数据分析、教练、雪具与场地一体化预约,钱包支付退款、订单核销与服务评价)
java·人工智能·spring boot·网络协议·数据分析·echarts