基于Redis注解缓存

搭建步骤

1.添加Spring Data Redis 依赖启动器
2.Redis服务连接配置
3.使用@Cacheable、@CachePut、@CacheEvict注解定制缓存管理
4.基于注解的Redis查询缓存测试
5.将缓存对象实现序列化
6.基于注解的Redis缓存查询测试
7.基于注解的Redis缓存更新测试
8.基于注解的Redis缓存删除测试

导入Redis依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

编写配置文件

spring.redis.host=127.0.0.1
#Redis服务器端口
spring.redis.port=6379
#Redis服务器连接密码 (默认为空)
spring.redis.password=

缓存基本搭建 

 Springboot 默认缓存-CSDN博客

 在Service层,使用@Cacheable@CachePut@CacheEvict注解定制缓存管理,并且需要加上@Transactional注解,否则在执行更新删除操作会报错

package com.gzlg.service;

import com.gzlg.bean.Comment;
import com.gzlg.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

@Service
@Transactional
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;

    /*
    * 查询:根据id查询
    * */
    //unless表示如果result==null,则不进行缓存
    @Cacheable(cacheNames = "comment",unless = "#result == null")  //对数据操作方法进行缓存管理 通常这个注解在Service类的查询方法上,对查询结果进行缓存
    public Comment findById(Integer id){
        Optional<Comment> byId = commentRepository.findById(id);
        if(byId.isPresent()){
            return byId.get();
        }
        return null;
    }


    /*
    * 更新
    * */
    //更新需要key值,将i的结果存为key值
    @CachePut(cacheNames = "comment",key = "#result.id")
    public Comment updateComment(Comment comment){
        commentRepository.update(comment.getAuthor(), comment.getId());
        Optional<Comment> byId = commentRepository.findById(comment.getId());
        if(byId.isPresent()){
            return byId.get();
        }
        return null;
    }


    /*
    * 删除
    * */
    @CacheEvict(cacheNames = "comment")
    public void deleteComment(Integer id){
        commentRepository.deleteById(id);
    }

}

实体类要实现序列化接口,否则会序列化错误

public class Comment implements Serializable {

 

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值