本篇随笔基于https://blog.csdn.net/weixin_41842236/article/details/104205713实现
一、使用Redis API进行业务数据缓存管理
在service下新建ApiCommentService,删除原有的CommentService
package com.uos.cache.service;
import com.uos.cache.domain.Comment;
import com.uos.cache.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@Service
public class ApiCommentService {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private CommentRepository commentRepository;
public Comment findById(int comment_id){
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();
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.getaId());
redisTemplate.opsForValue().set("comment_"+comment.getId(),comment);
return comment;
}
public void deleteComment(int comment_id){
commentRepository.deleteById(comment_id);
redisTemplate.delete("comment_"+comment_id);
}
}
二、在controller层下新建ApiCommentController
删除原有的CommentController
package com.uos.cache.controller;
import com.uos.cache.domain.Comment;
import com.uos.cache.service.ApiCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiCommentController {
@Autowired
private 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);
}
}
三、主程序类
四、效果测试
查询测试
更新测试
删除测试