P128

6.3.3基于API的Redis缓存实现

除了之前的基于注解形式的Redis缓存实现,还可以通过API的Redis缓存实现。(开发中常用)

1. 使用Redis API进行业务数据缓存管理。

在实验5-1的基础上,在项目的Service包里编写一个ApiCommentService类,使用@Autowired注解将RedisTemplate作为组件注入Spring容器,然后定义findById()、updateComment()、deleteComment()分别用与查询缓存、更新缓存以及删除缓存。(详情代码参考书本P128-129)

  1. package com.example.demo.Service;
  2. import java.util.Optional;
  3. import java.util.concurrent.TimeUnit;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.data.redis.core.RedisTemplate; //redis依赖包的RedisTemplate
  6. import org.springframework.stereotype.Service;
  7. import com.example.demo.Domain.Comment;
  8. import com.example.demo.Repository.CommentRepository;
  9. @Service
  10. public class ApiCommentService {
  11. @Autowired //通过@Autowired注解将Repository层的CommentRepository作为组件注入,以获取它下面的方法和属性
  12. private CommentRepository commentRepository;
  13. @Autowired //通过@Autowired注解将RedisTemplate作为组件注入Spring容器
  14. private RedisTemplate redisTemplate;
  15. //通过Comment类的findById方法重写,编写方法用于查询缓存
  16. public Comment findById(int comment_id) {
  17. //redisTemplate规定了类型为Object,定义object为Object类,获取缓存空间中的值
  18. Object object = redisTemplate.opsForValue().get("comment::"+comment_id); //获取comment::和接收的comment_id参数
  19. //如果缓存空间里有数据,返回object,并且将其强制转换成Comment
  20. if(object != null) {
  21. return (Comment)object;
  22. }else {
  23. Optional<Comment> optional = commentRepository.findById(comment_id); //如果没有数据,用从数据库获取相关数据用optional存储
  24. //如果获取到了,Comment类型comment存储optional的值,
  25. if(optional.isPresent()) {
  26. Comment comment = optional.get();
  27. //从缓存空间设置键名为comment::comment_id的comment,并且设置缓存有效期为1天时间
  28. redisTemplate.opsForValue().set("comment::"+comment_id, comment,1 ,TimeUnit.DAYS);
  29. return comment;
  30. }else {
  31. return null;
  32. }
  33. }
  34. }
  35. //编写更新缓存评论的方法
  36. public Comment updateComment(Comment comment) {
  37. commentRepository.updateComment(comment.getAuthor(), comment.getId());
  38. //更新数据后进行缓存更新
  39. redisTemplate.opsForValue().set("comment::"+comment.getId(), comment);
  40. return comment;
  41. }
  42. //编写删除缓存评论的方法
  43. public void deleteComment(int comment_id) {
  44. commentRepository.deleteById(comment_id);
  45. //删除数据后进行缓存删除
  46. redisTemplate.delete("comment::"+comment_id);
  47. }
  48. }

2. 在项目启动类添加相关注解开启基于注解的缓存支持。

添加相关注解到Service类的查询方法上,对查询结果进行缓存,开启Spring Boot默认支持的缓存,在浏览器输入相关的请求参数,查询数据,将相关的代码和浏览器的响应截图。(详情代码参考书本P119-120)

3. 添加Spring Data Redis依赖启动器

在全局配置文件中添加Redis服务连接配置,在Service文件中添加相关的缓存管理注解@Cacheable, @CachePut, @CacheEvict,在实体类Comment中实现序列化接口Serializable,在浏览器输入相关的请求参数,查询、更新、删除数据,将相关的代码和浏览器的响应截图。(详情代码参考书本P124-128)

image.png