基于注解的Redis缓存实现
步骤
添加Spring Data Redis 依赖启动器
Redis服务连接配置
注入依赖
添加配置
使用@Cacheable、@CachePut、@CacheEvict注解定制缓存管理
将缓存对象实现序列化
依赖
<!--redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.properties
spring.data.redis.host=127.0.0.1
spring.data.redis.port=6379
spring.data.redis.password=
service类
// 使用注解定制缓存管理 @Cacheable @CachePut @CacheEvict
import com.xy.demo.domain.Comment;
import com.xy.demo.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 java.util.Optional;
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
// 查询
@Cacheable(cacheNames = "comment",unless = "#result==null") // 表示将方法的返回结果缓存到名为 "comment" 的缓存中
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.getaId());
return comment;
}
// 删除
@CacheEvict(cacheNames = "comment")
public void deleteComment(int comment_id){
commentRepository.deleteById(comment_id);
}
}
实体类
// 将缓存对象实现序列化
import jakarta.persistence.*;
import java.io.Serializable;
@Entity(name = "t_comment")
public class Comment implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String content;
private String author;
@Column(name = "a_id")
private Integer aId;
}
测试前开启 redis 服务