6.3.3基于API的Redis缓存实现
除了之前的基于注解形式的Redis缓存实现,还可以通过API的Redis缓存实现。(开发中常用)
1. 使用Redis API进行业务数据缓存管理。
在实验5-1的基础上,在项目的Service包里编写一个ApiCommentService类,使用@Autowired注解将RedisTemplate作为组件注入Spring容器,然后定义findById()、updateComment()、deleteComment()分别用与查询缓存、更新缓存以及删除缓存。(详情代码参考书本P128-129)
package com.example.demo.Service;import java.util.Optional;import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate; //redis依赖包的RedisTemplateimport org.springframework.stereotype.Service;import com.example.demo.Domain.Comment;import com.example.demo.Repository.CommentRepository;@Servicepublic class ApiCommentService {@Autowired //通过@Autowired注解将Repository层的CommentRepository作为组件注入,以获取它下面的方法和属性private CommentRepository commentRepository;@Autowired //通过@Autowired注解将RedisTemplate作为组件注入Spring容器private RedisTemplate redisTemplate;//通过Comment类的findById方法重写,编写方法用于查询缓存public Comment findById(int comment_id) {//redisTemplate规定了类型为Object,定义object为Object类,获取缓存空间中的值Object object = redisTemplate.opsForValue().get("comment::"+comment_id); //获取comment::和接收的comment_id参数//如果缓存空间里有数据,返回object,并且将其强制转换成Commentif(object != null) {return (Comment)object;}else {Optional<Comment> optional = commentRepository.findById(comment_id); //如果没有数据,用从数据库获取相关数据用optional存储//如果获取到了,Comment类型comment存储optional的值,if(optional.isPresent()) {Comment comment = optional.get();//从缓存空间设置键名为comment::comment_id的comment,并且设置缓存有效期为1天时间redisTemplate.opsForValue().set("comment::"+comment_id, comment,1 ,TimeUnit.DAYS);return comment;}else {return null;}}}//编写更新缓存评论的方法public Comment updateComment(Comment comment) {commentRepository.updateComment(comment.getAuthor(), comment.getId());//更新数据后进行缓存更新redisTemplate.opsForValue().set("comment::"+comment.getId(), comment);return comment;}//编写删除缓存评论的方法public void deleteComment(int comment_id) {commentRepository.deleteById(comment_id);//删除数据后进行缓存删除redisTemplate.delete("comment::"+comment_id);}}
2. 在项目启动类添加相关注解开启基于注解的缓存支持。
添加相关注解到Service类的查询方法上,对查询结果进行缓存,开启Spring Boot默认支持的缓存,在浏览器输入相关的请求参数,查询数据,将相关的代码和浏览器的响应截图。(详情代码参考书本P119-120)
3. 添加Spring Data Redis依赖启动器
在全局配置文件中添加Redis服务连接配置,在Service文件中添加相关的缓存管理注解@Cacheable, @CachePut, @CacheEvict,在实体类Comment中实现序列化接口Serializable,在浏览器输入相关的请求参数,查询、更新、删除数据,将相关的代码和浏览器的响应截图。(详情代码参考书本P124-128)

