1.使用Redis API 進行業務數據緩存管理
編寫一個進行業務處理的類ApiCommentService,使用@Autowired注解注入Redis API中常用的RedisTemplate(類似于Java基礎API中的JdbcTemplate);
然后在數據查詢、修改和刪除三個方法中,根據業務需求分別進行數據緩存查詢、緩存存儲、緩存更新和緩存刪除。
同時,Comment數據對應緩存管理的key值都手動設置了一個前綴“comment_”,這是針對不同業務數據進行緩存管理設置的唯一key,避免與其他業務緩存數據的key重復。
@Service
public class ApiCommentService {@Autowiredprivate CommentRepository commentRepository;@Autowiredprivate RedisTemplate redisTemplate;public Comment findById(int comment_id){// 先從Redis緩存中查詢數據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();// 將查詢結果進行緩存,并設置有效期為1天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.getId());// 更新數據后進行緩存更新redisTemplate.opsForValue().set("comment_"+comment.getId(),comment);return comment;}public void deleteComment(int comment_id){commentRepository.deleteById(comment_id);// 刪除數據后進行緩存刪除redisTemplate.delete("comment_"+comment_id);}
}
2.創建Web訪問層類ApiCommentController
在類上加入了@RequestMapping(“/api”)注解用于窄化請求,
并通過@Autowired注解注入了新編寫的ApiCommentService實例對象,
然后調用ApiCommentService中的相關方法進行數據查詢、修改和刪除。
@RestController
@RequestMapping("/api") // 窄化請求路徑
public class ApiCommentController {@Autowiredprivate 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);}
}
3.基于API的Redis緩存實現的相關配置
- 基于API的Redis緩存實現不需要@EnableCaching注解開啟基于注解的緩存支持。
- 基于API的Redis緩存實現需要在Spring Boot項目的pom.xml文件中引入Redis依賴啟動器,并在配置文件中進行Redis服務連接配置,同時將進行數據存儲的Comment實體類實現序列化接口。
- 緩存測試與基于注解的Redis緩存實現的測試基本一樣,但訪問路徑加“/api”,如http://localhost:8080/api/get/2
4.做測試
http://localhost:8088/api/get/1
jdk序列化導致出現上圖紅色框的內容,無意義但會占據內存,所以要更改序列化方式