> 技术文档 > JavaWeb(苍穹外卖)--学习笔记13(微信小程序开发,缓存菜品,Spring Cache)

JavaWeb(苍穹外卖)--学习笔记13(微信小程序开发,缓存菜品,Spring Cache)


前言

本篇文章是学习B站黑马程序员苍穹外卖的学习笔记📑。我的学习路线是Java基础语法-JavaWeb-做项目,管理端的功能学习完之后,就进入到了用户端微信小程序的开发,小程序菜品数据是通过数据库获得,如果用户端访问量过大,数据库的压力会增加。

🔍通过Redis(之前说过他的临时存储功能)来缓存菜品数据,减少数据库查询操作。内存操作的性能比磁盘IO性能更高。

🙌通过实现小程序缓存菜品整个功能来了解Redis缓存功能

先通过流程图来了解一下整个程序执行过程:

JavaWeb(苍穹外卖)--学习笔记13(微信小程序开发,缓存菜品,Spring Cache)
直接看代码(缓存菜品):

 /** * 根据分类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);//查询起售中的菜品 //不存在,根据分类id查询数据库,将查询到的菜品数据缓存到redis中 list = dishService.listWithFlavor(dish); redisTemplate.opsForValue().set(key, list); return Result.success(list); }}

2.清除菜品缓存:

 /** * 新增菜品 * @param dishDTO * @return */ @PostMapping @ApiOperation(\"新增菜品\") public Result save(@RequestBody DishDTO dishDTO){ log.info(\"新增菜品:{}\", dishDTO); dishService.saveWithFlavor(dishDTO); //清理缓存数据 String key = \"dish_\" + dishDTO.getCategoryId(); redisTemplate.delete(key); return Result.success(); }

🔍SpringCache实现缓存更方便的工具

1. 什么是SpringCache?
Spring Cache 提供了一套统一的注解和接口,使得开发者可以轻松地将缓存功能集成到应用中,而不需要关心底层缓存的具体实现(如 Redis、Ehcache 等)。

Spring Cache:提供了更高层次的抽象,通过注解(如 @Cacheable, @CachePut, @CacheEvict)简化了缓存的操作。

2. 来看看Spring Cache常用注解:

JavaWeb(苍穹外卖)--学习笔记13(微信小程序开发,缓存菜品,Spring Cache)
3. Spring Cache的配置使用

application.xml文件:

 redis: host: localhost port: 6379 password: 123456 database: 0

加入依赖:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>

然后就可以添加注解了:

在Controller层添加如下注解:
@Cacheable(cacheNames = “setmealCache”, key = “#categoryId”)

 /** * 条件查询 * * @param categoryId * @return */ @GetMapping(\"/list\") @ApiOperation(\"根据分类id查询套餐\") @Cacheable(cacheNames = \"setmealCache\", key = \"#categoryId\")//缓存套餐数据key:setmealCache:categoryId public Result<List<Setmeal>> list(Long categoryId) { Setmeal setmeal = new Setmeal(); setmeal.setCategoryId(categoryId); setmeal.setStatus(StatusConstant.ENABLE); List<Setmeal> list = setmealService.list(setmeal); return Result.success(list); }

发出请求执行方法就可以看到缓存中有数据了

JavaWeb(苍穹外卖)--学习笔记13(微信小程序开发,缓存菜品,Spring Cache)

小白啊!!!写的不好轻喷啊🤯如果觉得写的不好,点个赞吧🤪(批评是我写作的动力)

…。。。。。。。。。。。…JavaWeb(苍穹外卖)--学习笔记13(微信小程序开发,缓存菜品,Spring Cache)

…。。。。。。。。。。。…