基于注解的Redis缓存实现

使用@Cacheable、@CachePut、@CacheEvict注解定制缓存管理

对CommentService类中的方法进行修改使用@Cacheable、@CachePut、@CacheEvict三个注解定制缓存管理,修改后的方法如下:

@Cacheable(cacheNames = "comment",unless = "#result==null")
public Comment findById(int comment_id){

    Optional optional = commentRepository.findById(comment_id);
    if(optional.isPresent()){
        return optional.get();
    }
return null;
}

@CachePut(cacheNames = "comment",key = "#result.id")
public Comment updateComment(Comment comment){

    commentRepository.updateComment(comment.getAuthor(), comment.getId());
    return comment;

}

@CacheEvict(cacheNames = "comment")
public void deleteComment(int comment_id){

    commentRepository.deleteById(comment_id);

}

基于注解的Redis查询缓存测试

项目启动成功后,通过浏览器访问http://localhost:8088/get/1,如果控制台显示如下:

......

Hibernate: select comment0_.id as id1_0_0_, comment0_.a_id as a_id2_0_0_, comment0_.author as author3_0_0_, commen.......
......
java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.itheima.my06.entity.Comment]
......

需要对实体类进行序列化,对Comment修改如下:

public class Comment implements Serializable

再次测试,并重复刷新浏览器,只出现一条sql语句

基于注解的Redis缓存实现_第1张图片

打开Redis客户端可视化管理工具Redis Desktop Manager,连接本地启用的Redis服务

基于注解的Redis缓存实现_第2张图片

可以看出,评论存储到了redis缓存库中comment名称空间下,key=comment::1,value=经过JDK默认序列化格式后的HEX格式值,不方便查看,需要自定义数据的序列化格式。

基于注解的Redis缓存更新测试

项目启动成功后,通过浏览器访问http://localhost:8088/update/1/shitou,结果如下:

基于注解的Redis缓存实现_第3张图片

查看缓存,已经改过来了,如下图:

基于注解的Redis缓存实现_第4张图片

执行updateComment()方法时只会执行一条更新SQL语句

基于注解的Redis缓存实现_第5张图片

基于注解的Redis缓存删除测试

项目启动成功后,通过Redis客户端可视化管理工具Redis Desktop Manager查看缓存信息。

如果不存在缓存,通过浏览器访问http://localhost:8088/get/1,缓存数据,

再次通过Redis Desktop Manager查看,reload下

基于注解的Redis缓存实现_第6张图片

基于注解的Redis缓存实现_第7张图片

接着访问http://localhost:8088/delete/1

reload,查看缓存信息,该条缓存被删除

基于注解的Redis缓存实现_第8张图片

基于注解的Redis缓存实现_第9张图片

你可能感兴趣的:(springboot,缓存,redis,数据库)