基于注解的Redis缓存实现

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

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

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

    Optional<Comment> 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客户端可视化管理工具Redis Desktop Manager,连接本地启用的Redis服务

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

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

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

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

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

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

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

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

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值