关闭页面特效

redis练习

1|0redis相关练习


1|1内容


  • 环境搭建
  • 缓存短信验证码
  • 缓存菜品信息
  • SpringCache
  • 缓存套餐数据

1|2前言


1). 当前系统存在的问题

之前我们已经实现了移动端菜品展示、点餐、购物车、下单等功能,但是由于移动端是面向所有的消费者的,请求压力相对比较大,而我们当前所有的数据查询都是从数据库MySQL中直接查询的,那么可能就存在如下问题: 频繁访问数据库,数据库访问压力大,系统性能下降,用户体验较差。

image-20230720155309860

image-20230720155319379

2). 解决该问题的方法

要解决我们上述提到的问题,就可以使用我们前面学习的一个技术:Redis,通过Redis来做缓存,从而降低数据库的访问压力,提高系统的访问性能,从而提升用户体验。加入Redis做缓存之后,我们在进行数据查询时,就需要先查询缓存,如果缓存中有数据,直接返回,如果缓存中没有数据,则需要查询数据库,再将数据库查询的结果,缓存在redis中。

环境准备

1). 在项目的pom.xml文件中导入spring data redis的maven坐标

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

2). 在项目的application.yml中加入redis相关配置

redis: host: 192.168.206.128 port: 6379 database: 0 jedis: pool: max-active: 10 max-idle: 5

注意: 引入上述依赖时,需要注意yml文件前面的缩进,上述配置应该配置在spring层级下面。

3). 编写Redis的配置类RedisConfig,定义RedisTemplate

package com.tyhxzy.reggie.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig { @Bean(name="redisTemplate") public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(new StringRedisSerializer()); //由于GenericJackson2JsonRedisSerializer这个序列化器对待LocalDateTime类型字段进行序列化的时候给LocaDatetime对象增加了很多的字段, //导致反序列会失败。 解决方案: //template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } }

解释说明:

1). 在SpringBoot工程启动时, 会加载一个自动配置类 RedisAutoConfiguration, 在里面已经声明了RedisTemplate这个bean

image-20230720155336059

上述框架默认声明的RedisTemplate用的key和value的序列化方式是默认的 JdkSerializationRedisSerializer,如果key采用这种方式序列化,最终我们在测试时通过redis的图形化界面查询不是很方便,如下形式:

image-20230720155348631

2). 如果使用我们自定义的RedisTemplate, key的序列化方式使用的是StringRedisSerializer, 也就是字符串形式, 最终效果如下:

image-20230720155358177

3). 定义了两个bean会不会出现冲突呢? 答案是不会, 因为源码如下:

image-20230720155411229

1|3缓存短信验证码


思路分析

前面我们已经实现了移动端手机验证码登录,随机生成的验证码我们是保存在HttpSession中的。但是在我们实际的业务场景中,一般验证码都是需要设置过期时间的,如果存在HttpSession中就无法设置过期时间,此时我们就需要对这一块的功能进行优化。

现在需要改造为将验证码缓存在Redis中,具体的实现思路如下:

1). 在服务端UserController中注入RedisTemplate对象,用于操作Redis;

2). 在服务端UserController的sendMsg方法中,将随机生成的验证码缓存到Redis中,并设置有效期为5分钟;

3). 在服务端UserController的login方法中,从Redis中获取缓存的验证码,如果登录成功则删除Redis中的验证码;

代码改造

1). 在UserController中注入RedisTemplate对象,用于操作Redis

@Autowired private RedisTemplate redisTemplate;

2). 在UserController的sendMsg方法中,将生成的验证码保存到Redis

image-20230720155425034

package com.tyhxzy.reggie.controller; import com.tyhxzy.reggie.common.R; import com.tyhxzy.reggie.entity.User; import com.tyhxzy.reggie.service.UserService; import com.tyhxzy.reggie.utils.SMSUtils; import com.tyhxzy.reggie.utils.ValidateCodeUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; import java.util.Map; import java.util.concurrent.TimeUnit; @RestController @RequestMapping("/user") @Slf4j public class UserController { @Autowired private UserService userService; @Autowired private RedisTemplate redisTemplate; /** * {phone:18000110011} * 作用:发送验证码 * @return */ @PostMapping("/sendMsg") public R sendMsg(@RequestBody User user){ //1. 生成随机验证码 String verifyCode = "1234";//ValidateCodeUtils.generateValidateCode(4)+""; log.info("本次生成的验证码:"+verifyCode); //2. 发送信息 直接在控制台上去查看就可以了。主要是方便我们去登录,不是钱不钱问题了。 // SMSUtils.sendMessage("黑马旅游网","SMS_205126318",user.getPhone(),verifyCode); //3. 生成的验证码你需要保存到session,session过期时间默认是30分钟,时间太长,不适用于验证码,我们可以考虑使用Redis /// session.setAttribute("verifyCode_"+user.getPhone(),verifyCode); ValueOperations valueOperations = redisTemplate.opsForValue(); valueOperations.set("verifyCode_"+user.getPhone(),verifyCode,1, TimeUnit.MINUTES); //设置多少分钟失效,验证码一般是1分钟失效 return R.success("发送成功"); } }
  1. 登陆校验代码需要从redis中取出数据

image-20230720155440418

package com.tyhxzy.reggie.controller; import com.tyhxzy.reggie.common.R; import com.tyhxzy.reggie.entity.User; import com.tyhxzy.reggie.service.UserService; import com.tyhxzy.reggie.utils.SMSUtils; import com.tyhxzy.reggie.utils.ValidateCodeUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; import java.util.Map; import java.util.concurrent.TimeUnit; @RestController @RequestMapping("/user") @Slf4j public class UserController { @Autowired private UserService userService; @Autowired private RedisTemplate redisTemplate; /** *作用:登录 * 请求url: http://localhost:8080/user/login * 请求方式: post请求 *请求数据:{ "phone": "18000110011", "code": "1234" } map.put("phone","18000110011") map.put("code","1234"); */ @PostMapping("/login") public R login(@RequestBody Map<String,String> param,HttpSession session){ //1. 取出客户提交手机号与验证码 String phone = param.get("phone"); String code = param.get("code"); //用户输入 //2. 从redis中取出验证码 // String verifyCode = (String) session.getAttribute("verifyCode_"+phone); //系统生成验证码 ValueOperations valueOperations = redisTemplate.opsForValue(); String verifyCode = (String) valueOperations.get("verifyCode_" + phone); //3. 交给service去校验 User user = userService.login(phone,code,verifyCode); if(user!=null){ //登录成功我需要在session中做一个登录成功标记 session.setAttribute("user",user.getId()); //删除验证码 redisTemplate.delete("verifyCode_" + phone); } return R.success("登录成功"); } }

功能测试

代码编写完毕之后,重启服务。

1). 访问前端工程,获取验证码

image-20230720155454404

通过控制台的日志,我们可以看到生成的验证码:

image-20230720155503744

2). 通过Redis的图形化界面工具查看Redis中的数据

image-20230720155511668

3). 在登录界面填写验证码登录完成后,查看Redis中的数据是否删除

image-20230720155519501

1|4缓存app信息


实现思路

前面我们已经实现了移动端菜品查看功能,对应的服务端方法为DishController的list方法,此方法会根据前端提交的查询条件(categoryId)进行数据库查询操作。在高并发的情况下,频繁查询数据库会导致系统性能下降,服务端响应时间增长。现在需要对此方法进行缓存优化,提高系统的性能。

那么,我们又需要思考一个问题, 具体缓存几份数据呢, 所有的菜品缓存一份 , 还是说需要缓存多份呢? 我们可以看一下我们之前做的移动端效果:

image-20230720155530669

我们点击哪一个分类,展示的就是该分类下的菜品, 其他菜品无需展示。所以,这里面我们在缓存时,可以根据菜品的分类,缓存多份数据,页面在查询时,点击的是哪个分类,我们就查询该分类下的菜品缓存数据。

具体的实现思路如下:

1). 改造DishServiceImpl的list方法,先从Redis中获取分类对应的菜品数据,如果有则直接返回,无需查询数据库;如果没有则查询数据库,并将查询到的菜品数据存入Redis。

2). 改造DishController的save和update方法,加入清理缓存的逻辑。

注意:

​ 在使用缓存过程中,要注意保证数据库中的数据和缓存中的数据一致,如果数据库中的数据发生变化,需要及时清理缓存数据。否则就会造成缓存数据与数据库数据不一致的情况。

代码改造

需要改造的代码为: DishServiceImpl

查询菜品缓存

改造的方法 redis的数据类型 redis缓存的key redis缓存的value
list string dish_分类Id_状态 , 比如: dish_12323232323_1 List

1). 在DishServiceImpl中注入RedisTemplate

@Autowired private RedisTemplate redisTemplate;

2). 在list方法中,查询数据库之前,先查询缓存, 缓存中有数据, 直接返回

package com.tyhxzy.reggie.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.tyhxzy.reggie.dao.CategoryDao; import com.tyhxzy.reggie.dao.DishDao; import com.tyhxzy.reggie.dao.DishFlavorDao; import com.tyhxzy.reggie.entity.Category; import com.tyhxzy.reggie.entity.Dish; import com.tyhxzy.reggie.entity.DishFlavor; import com.tyhxzy.reggie.entity.Page; import com.tyhxzy.reggie.entity.dto.DishDto; import com.tyhxzy.reggie.service.DishService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @Service public class DishServiceImpl implements DishService { @Autowired(required = false) private DishDao dishDao; @Autowired(required = false) private DishFlavorDao dishFlavorDao; @Autowired(required = false) private CategoryDao categoryDao; @Autowired private RedisTemplate redisTemplate; /** * 使用缓存思路: * 1. 请求过来获取数据的时候先问redis获取 * 2. 如果redis有数据直接从redis中返回 * 3. 如果redis没有数据,查询数据库,查询的结果存储到redis中。 * * @param categoryId 类别的id * @param status * @return */ @Override public List<DishDto> list(Long categoryId,Integer status) { List<DishDto> dishDtoList = null; ValueOperations valueOperations = redisTemplate.opsForValue(); // 1. 请求过来获取数据的时候先问redis获取 String key = "dish_"+categoryId+"_"+status; if(valueOperations.get(key)!=null){ dishDtoList = (List<DishDto>) valueOperations.get(key); }else { //如果redis中没有对应的缓存数据,那么我们就直接查询数据库,然后把查询的结果保存到redis中。 List<Dish> dishList = dishDao.findByCategoryId(categoryId, status); //遍历所有的菜品,然后查询每一个菜品对应的口味,然后封装到DTO里面 dishDtoList = dishList.stream().map(dish -> { DishDto dishDto = new DishDto(); //属性拷贝 BeanUtils.copyProperties(dish, dishDto); //查询菜品对应口味 List<DishFlavor> flavorList = dishFlavorDao.findByDishId(dish.getId()); dishDto.setFlavors(flavorList); return dishDto; }).collect(Collectors.toList()); valueOperations.set(key,dishDtoList,1, TimeUnit.DAYS);//一天的有效时间 } return dishDtoList; } }

清理菜品缓存

为了保证数据库中的数据和缓存中的数据一致,如果数据库中的数据发生变化,需要及时清理缓存数据。所以,我们需要在添加菜品、更新菜品时清空缓存数据。

1). 保存菜品,清空缓存

在保存菜品的方法save中,当菜品数据保存完毕之后,需要清空菜品的缓存。那么这里清理菜品缓存的方式存在两种:

A. 清理所有分类下的菜品缓存

//清理所有菜品的缓存数据 Set keys = redisTemplhate.keys("dish_*"); //获取所有以dish_xxx开头的key redisTemplate.delete(keys); //删除这些key

B. 清理当前添加菜品分类下的缓存

//清理某个分类下面的菜品缓存数据 String key = "dish_" + dishDto.getCategoryId(); redisTemplate.delete(key);

注意: 在这里我们推荐使用第一种方式进行清理,这样逻辑更加严谨。 因为对于修改操作,用户是可以修改菜品的分类的,如果用户修改了菜品的分类,那么原来分类下将少一个菜品,新的分类下将多一个菜品,这样的话,两个分类下的菜品列表数据都发生了变化。

DishServiceImpl 保存新增菜品

@Service public class DishServiceImpl implements DishService { @Autowired(required = false) private DishDao dishDao; @Autowired(required = false) private DishFlavorDao dishFlavorDao; @Autowired(required = false) private CategoryDao categoryDao; @Autowired private RedisTemplate redisTemplate; /** * 菜品的添加 * @param dishDto */ @Transactional @Override public void save(DishDto dishDto)

image-20230720155554003

DishServiceImpl 保存更新菜品

@Service public class DishServiceImpl implements DishService { @Autowired(required = false) private DishDao dishDao; @Autowired(required = false) private DishFlavorDao dishFlavorDao; @Autowired(required = false) private CategoryDao categoryDao; @Autowired private RedisTemplate redisTemplate; /** * 菜品的添加 * @param dishDto */ @Transactional @Override public void save(DishDto dishDto)

image-20230720155604955

功能测试

代码编写完毕之后,重新启动服务。

1). 访问移动端,根据分类查询菜品列表,然后再检查Redis的缓存数据,是否可以正常缓存;

image-20230720155622412

我们也可以在服务端,通过debug断点的形式一步一步的跟踪代码的执行。

2). 当我们在进行新增及修改菜品时, 查询Redis中的缓存数据, 是否被清除;

1|5Spring Cache


介绍

Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能,大大简化我们在业务中操作缓存的代码。

Spring Cache只是提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。CacheManager是Spring提供的各种缓存技术抽象接口。

针对不同的缓存技术需要实现不同的CacheManager:

CacheManager 描述
EhCacheCacheManager 使用EhCache作为缓存技术
GuavaCacheManager 使用Google的GuavaCache作为缓存技术
RedisCacheManager 使用Redis作为缓存技术
spring 自己也搞了一套缓存技术,默认的缓存
spring缓存是缓存在Map集合中

注解

在SpringCache中提供了很多缓存操作的注解,常见的是以下的几个:

注解 说明
@EnableCaching 开启缓存注解功能
@Cacheable 在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
@CachePut 将方法的返回值或者参数放到缓存中
@CacheEvict 将一条或多条数据从缓存中删除

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

例如,使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可。

入门程序

接下来,我们将通过一个入门案例来演示一下SpringCache的常见用法。 上面我们提到,SpringCache可以集成不同的缓存技术,如Redis、Ehcache甚至我们可以使用Map来缓存数据, 接下来我们在演示的时候,就先通过一个Map来缓存数据,最后我们再换成Redis来缓存。

环境准备

1). 数据库准备

将今天资料中的SQL脚本直接导入数据库中。

image-20230720155647118

2). 导入基础工程

基础环境的代码,在我们今天的资料中已经准备好了, 大家只需要将这个工程导入进来就可以了。导入进来的工程结构如下:

image-20230720155655224

由于SpringCache的基本功能是Spring核心(spring-context)中提供的,所以目前我们进行简单的SpringCache测试,是可以不用额外引入其他依赖的。

3). 注入CacheManager

我们可以在UserController注入一个CacheManager,在Debug时,我们可以通过CacheManager跟踪缓存中数据的变化。

image-20230720155705722

我们可以看到CacheManager是一个接口,默认的实现有以下几种 ;

image-20230720155715715

而在上述的这几个实现中,默认使用的是 ConcurrentMapCacheManager。稍后我们可以通过断点的形式跟踪缓存数据的变化。

4). 引导类上加@EnableCaching

在引导类上加该注解,就代表当前项目开启缓存注解功能。

image-20230720155723967

@CachePut注解

@CachePut 说明:

​ 作用: 将方法返回值,放入缓存

​ value: 缓存的名称, 每个缓存名称下面可以有很多key

​ key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法

1). 在save方法上加注解@CachePut

当前UserController的save方法是用来保存用户信息的,我们希望在该用户信息保存到数据库的同时,也往缓存中缓存一份数据,我们可以在save方法上加上注解 @CachePut,用法如下:

/** * CachePut:将方法返回值放入缓存 * value:缓存的名称,每个缓存名称下面可以有多个key * key:缓存的key */ @CachePut(value = "userCache", key = "#user.id") @PostMapping public User save(User user){ userService.save(user); return user; }

key的写法如下:

​ #user.id : #user指的是方法形参的名称, id指的是user的id属性 , 也就是使用user的id属性作为key ;

​ #user.name: #user指的是方法形参的名称, name指的是user的name属性 ,也就是使用user的name属性作为key ;

​ #result.id : #result代表方法返回值,该表达式 代表以返回对象的id属性作为key ;

​ #result.name : #result代表方法返回值,该表达式 代表以返回对象的name属性作为key ;

2). 测试

启动服务,通过postman请求访问UserController的方法, 然后通过断点的形式跟踪缓存数据。

image-20230720155735574

第一次访问时,缓存中的数据是空的,因为save方法执行完毕后才会缓存数据。

image-20230720155746101

第二次访问时,我们通过debug可以看到已经有一条数据了,就是上次保存的数据,已经缓存了,缓存的key就是用户的id。

image-20230720155833777

注意: 上述的演示,最终的数据,实际上是缓存在ConcurrentHashMap中,那么当我们的服务器重启之后,缓存中的数据就会丢失。 我们后面使用了Redis来缓存就不存在这样的问题了。

@CacheEvict注解

@CacheEvict 说明:

​ 作用: 清理指定缓存

​ value: 缓存的名称,每个缓存名称下面可以有多个key

​ key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法

1). 在 delete 方法上加注解@CacheEvict

当我们在删除数据库user表的数据的时候,我们需要删除缓存中对应的数据,此时就可以使用@CacheEvict注解, 具体的使用方式如下:

/** * CacheEvict:清理指定缓存 * value:缓存的名称,每个缓存名称下面可以有多个key * key:缓存的key */ @CacheEvict(value = "userCache",key = "#p0") //#p0 代表第一个参数 //@CacheEvict(value = "userCache",key = "#root.args[0]") //#root.args[0] 代表第一个参数 //@CacheEvict(value = "userCache",key = "#id") //#id 代表变量名为id的参数 @DeleteMapping("/{id}") public void delete(@PathVariable Long id){ userService.removeById(id); }

2). 测试

要测试缓存的删除,我们先访问save方法4次,保存4条数据到数据库的同时,也保存到缓存中,最终我们可以通过debug看到缓存中的数据信息。 然后我们在通过postman访问delete方法, 如下:

image-20230720155848072

删除数据时,通过debug我们可以看到已经缓存的4条数据:

image-20230720155859145

当执行完delete操作之后,我们再次保存一条数据,在保存的时候debug查看一下删除的ID值是否已经被删除。

image-20230720155907750

3). 在 update 方法上加注解@CacheEvict

在更新数据之后,数据库的数据已经发生了变更,我们需要将缓存中对应的数据删除掉,避免出现数据库数据与缓存数据不一致的情况。

//@CacheEvict(value = "userCache",key = "#p0.id") //第一个参数的id属性 //@CacheEvict(value = "userCache",key = "#user.id") //参数名为user参数的id属性 //@CacheEvict(value = "userCache",key = "#root.args[0].id") //第一个参数的id属性 @CacheEvict(value = "userCache",key = "#result.id") //返回值的id属性 @PutMapping public User update(User user){ userService.updateById(user); return user; }

加上注解之后,我们可以重启服务,然后测试方式,基本和上述相同,先缓存数据,然后再更新某一条数据,通过debug的形式查询缓存数据的情况。

@Cacheable注解

@Cacheable 说明:

​ 作用: 在方法执行前,spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中

​ value: 缓存的名称,每个缓存名称下面可以有多个key

​ key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法

1). 在getById上加注解@Cacheable

/** * Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中 * value:缓存的名称,每个缓存名称下面可以有多个key * key:缓存的key */ @Cacheable(value = "userCache",key = "#id") @GetMapping("/{id}") public User getById(@PathVariable Long id){ User user = userService.getById(id); return user; }

2). 测试

我们可以重启服务,然后通过debug断点跟踪程序执行。我们发现,第一次访问,会请求我们controller的方法,查询数据库。后面再查询相同的id,就直接获取到数据库,不用再查询数据库了,就说明缓存生效了。

image-20230720155924180

当我们在测试时,查询一个数据库不存在的id值,第一次查询缓存中没有,也会查询数据库。而第二次再查询时,会发现,不再查询数据库了,而是直接返回,那也就是说如果根据ID没有查询到数据,那么会自动缓存一个null值。 我们可以通过debug,验证一下:

image-20230720155935078

我们能不能做到,当查询到的值不为null时,再进行缓存,如果为null,则不缓存呢? 答案是可以的。

3). 缓存非null值

在@Cacheable注解中,提供了两个属性分别为: condition, unless 。

condition : 表示满足什么条件, 再进行缓存 ;

unless : 表示满足条件则不缓存 ; 与上述的condition是反向的 ;

具体实现方式如下:

@GetMapping("/{id}") /** * @CacheAble 查询的时候先检查缓存中是否存在该缓存,如果不存在该缓存,那么把结果缓存起来。如果存在该缓存直接返回缓存的数据 * * 存在问题: 返回的结果即使是null值也会生成缓存。 * condition: 生成缓存的条件,如果等于true生成缓存,注意:condition不能使用result返回值的 * unless: 不生成缓存的条件,与condition相反的 */ @Cacheable(value = "users",key="#id",unless = "#result==null") public User getById(@PathVariable Long id){ User user = userService.findById(id); return user; }

注意: 此处,我们使用的时候只能够使用 unless, 因为在condition中,我们是无法获取到结果 #result的。

集成Redis

在使用上述默认的ConcurrentHashMap做缓存时,服务重启之后,之前缓存的数据就全部丢失了,操作起来并不友好。在项目中使用,我们会选择使用redis来做缓存,主要需要操作以下几步:

1). pom.xml

<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>

2). application.yml

spring: redis: host: 192.168.200.200 port: 6379 cache: redis: time-to-live: 1800000 #单位毫秒,设置缓存过期时间,可选

3). 测试

重新启动项目,通过postman发送根据id查询数据的请求,然后通过redis的图形化界面工具,查看redis中是否可以正常的缓存数据。

image-20230720155947453

image-20230720155954247

1|6缓存套餐数据


实现思路

前面我们已经实现了移动端套餐查看功能,对应的服务端方法为SetmealController的list方法,此方法会根据前端提交的查询条件进行数据库查询操作。在高并发的情况下,频繁查询数据库会导致系统性能下降,服务端响应时间增长。现在需要对此方法进行缓存优化,提高系统的性能。

具体的实现思路如下:

1). 导入Spring Cache和Redis相关maven坐标

2). 在application.yml中配置缓存数据的过期时间

3). 在启动类上加入@EnableCaching注解,开启缓存注解功能

4). 在SetmealController的list方法上加入@Cacheable注解

5). 在SetmealController的save和delete方法上加入CacheEvict注解

缓存套餐数据

代码实现

1). pom.xml中引入依赖

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

备注: spring-boot-starter-data-redis 这个依赖前面已经引入了, 无需再次引入。

2). application.yml中设置缓存过期时间

spring: cache: redis: time-to-live: 1800000 #设置缓存数据的过期时间

3). 启动类上加入@EnableCaching注解

image-20230720160051378

4). SetmealServiceImpl的list方法上加入@Cacheable注解

在进行套餐数据查询时,我们需要根据分类ID和套餐的状态进行查询,所以我们在缓存数据时,可以将套餐分类ID和套餐状态组合起来作为key,如: 1627182182_1 (1627182182为分类ID,1为状态)。

/** * 作用:根据类别查询套餐 * @param categoryId * @param status * @return */ @Override @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status") public List<SetmealDto> list(Long categoryId, Integer status) { List<Setmeal> setmealList = setmealDao.list(categoryId,status); //转成Dto List<SetmealDto> setmealDtoList = setmealList.stream().map(setmeal -> { SetmealDto setmealDto = new SetmealDto(); //属性拷贝 BeanUtils.copyProperties(setmeal, setmealDto); //查询套餐对应菜品 List<SetmealDish> setmealDishList = setmealDishDao.findBySetmealId(setmeal.getId()); setmealDto.setSetmealDishes(setmealDishList); return setmealDto; }).collect(Collectors.toList()); return setmealDtoList; }

清理套餐数据

代码实现

为了保证数据库中数据与缓存数据的一致性,在我们添加套餐或者删除套餐数据之后,需要清空当前套餐缓存的全部数据。那么@CacheEvict注解如何清除某一份缓存下所有的数据呢,这里我们可以指定@CacheEvict中的一个属性 allEnties,将其设置为true即可。

1). 在saveWithDish方法上加注解@CacheEvict

package com.tyhxzy.reggie.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.tyhxzy.reggie.dao.CategoryDao; import com.tyhxzy.reggie.dao.DishDao; import com.tyhxzy.reggie.dao.SetmealDao; import com.tyhxzy.reggie.dao.SetmealDishDao; import com.tyhxzy.reggie.entity.*; import com.tyhxzy.reggie.entity.dto.SetmealDto; import com.tyhxzy.reggie.entity.vo.SetmealDishVo; import com.tyhxzy.reggie.exception.CustomerException; import com.tyhxzy.reggie.service.SetmealService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; @Service public class SetmealServiceImpi implements SetmealService { @Autowired(required = false) private SetmealDao setmealDao; @Autowired(required = false) private SetmealDishDao setmealDishDao; @Autowired(required = false) private CategoryDao categoryDao; /** * 保存套餐 * @param setmealDto */ @Override @Transactional @CacheEvict(value = "setmealCache",allEntries =true ) // allEntries =true 该名称空间下的所有缓存全部清楚 public void save(SetmealDto setmealDto) { //1. 给套餐的信息补全参数(创建时间修改时间,状态) setmealDto.setCreateTime(LocalDateTime.now()); setmealDto.setUpdateTime(LocalDateTime.now()); setmealDto.setStatus(1); //1启售, 0禁售 setmealDao.save(setmealDto); //由于下面需要使用到套餐的id,所以插入之后记得返回主键。 //2. 给套餐的菜品补全参数 List<SetmealDish> dishList = setmealDto.getSetmealDishes(); for (SetmealDish setmealDish : dishList) { setmealDish.setSetmealId(setmealDto.getId()); //所属的套餐 setmealDish.setSort(0); //排序 setmealDish.setCreateUser(setmealDto.getCreateUser()); setmealDish.setUpdateUser(setmealDto.getUpdateUser()); setmealDish.setCreateTime(setmealDto.getCreateTime()); setmealDish.setUpdateTime(setmealDto.getUpdateTime()); } //批量插入套餐菜品 setmealDishDao.batchSave(dishList); } }

测试

代码编写完成之后,重启工程,然后访问后台管理系统,对套餐数据进行新增 以及 删除, 然后通过Redis的图形化界面工具,查看Redis中的套餐缓存是否已经被删除。


__EOF__

作  者YXH
出  处https://www.cnblogs.com/YxinHaaa/p/17573436.html
关于博主:编程路上的小学生,热爱技术,喜欢专研。评论和私信会在第一时间回复。或者直接私信我。
版权声明:署名 - 非商业性使用 - 禁止演绎,协议普通文本 | 协议法律文本
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!

posted @   YxinHaaa  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
0
0
关注
跳至底部
点击右上角即可分享
微信分享提示