1.使用Redis API 进行业务数据缓存管理
编写一个进行业务处理的类ApiCommentService,使用@Autowired注解注入Redis API中常用的RedisTemplate(类似于Java基础API中的JdbcTemplate);
然后在数据查询、修改和删除三个方法中,根据业务需求分别进行数据缓存查询、缓存存储、缓存更新和缓存删除。
同时,Comment数据对应缓存管理的key值都手动设置了一个前缀“comment_”,这是针对不同业务数据进行缓存管理设置的唯一key,避免与其他业务缓存数据的key重复。
@Service
public class ApiCommentService {@Autowiredprivate CommentRepository commentRepository;@Autowiredprivate RedisTemplate redisTemplate;public Comment findById(int comment_id){// 先从Redis缓存中查询数据Object object = redisTemplate.opsForValue().get("comment_"+comment_id);if (object!=null){return (Comment)object;}else {// 缓存中没有,就进入数据库查询Optional<Comment> optional = commentRepository.findById(comment_id);if(optional.isPresent()){Comment comment= optional.get();// 将查询结果进行缓存,并设置有效期为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.创建Web访问层类ApiCommentController
在类上加入了@RequestMapping(“/api”)注解用于窄化请求,
并通过@Autowired注解注入了新编写的ApiCommentService实例对象,
然后调用ApiCommentService中的相关方法进行数据查询、修改和删除。
@RestController
@RequestMapping("/api") // 窄化请求路径
public class ApiCommentController {@Autowiredprivate ApiCommentService apiCommentService;@GetMapping("/get/{id}")public Comment findById(@PathVariable("id") int comment_id){Comment comment = apiCommentService.findById(comment_id);return comment;}@GetMapping("/update/{id}/{author}")public Comment updateComment(@PathVariable("id") int comment_id,@PathVariable("author") String author){Comment comment = apiCommentService.findById(comment_id);comment.setAuthor(author);Comment updateComment = apiCommentService.updateComment(comment);return updateComment;}@GetMapping("/delete/{id}")public void deleteComment(@PathVariable("id") int comment_id){apiCommentService.deleteComment(comment_id);}
}
3.基于API的Redis缓存实现的相关配置
- 基于API的Redis缓存实现不需要@EnableCaching注解开启基于注解的缓存支持。
- 基于API的Redis缓存实现需要在Spring Boot项目的pom.xml文件中引入Redis依赖启动器,并在配置文件中进行Redis服务连接配置,同时将进行数据存储的Comment实体类实现序列化接口。
- 缓存测试与基于注解的Redis缓存实现的测试基本一样,但访问路径加“/api”,如http://localhost:8080/api/get/2
4.做测试
http://localhost:8088/api/get/1
jdk序列化导致出现上图红色框的内容,无意义但会占据内存,所以要更改序列化方式