SpringCache進行緩存數(shù)據(jù)庫查詢
1、在SpringBoot的啟動類上添加注解@EnableCaching
開啟SpringCache緩存支持
@SpringBootApplication // 開啟SpringCache緩存支持 @EnableCaching public class GatheringApplication { public static void main(String[] args) { SpringApplication.run(GatheringApplication.class, args); } }
2、在service的方法上添加對應(yīng)的注解
/** * 根據(jù)ID查詢 * * @param id * @return */ // 使用SpringCache進行緩存數(shù)據(jù)庫查詢 @Cacheable(value = "gathering", key = "#id") public Gathering findById(String id) { return gatheringDao.findById(id).get(); } /** * 修改 * * @param gathering */ // 修改數(shù)據(jù)庫數(shù)據(jù)后需要刪除redis中的緩存 @CacheEvict(value = "gathering", key = "#gathering.id") public void update(Gathering gathering) { gatheringDao.save(gathering); } /** * 刪除 * * @param id */ // 刪除數(shù)據(jù)庫數(shù)據(jù)后需要刪除redis中的緩存 @CacheEvict(value = "gathering", key = "#id") public void deleteById(String id) { gatheringDao.deleteById(id); }
SpringCache 數(shù)據(jù)庫一致性問題
緩存和數(shù)據(jù)庫不一致的問題
先更新數(shù)據(jù)庫,再更新緩存
先更新數(shù)據(jù)庫更新成功了,但是更新redis的時候失敗了,這就導(dǎo)致了數(shù)據(jù)庫和Redis里面的數(shù)據(jù)不一致,
解決辦法
先更新緩存,再更新數(shù)據(jù)庫,更新緩存的時候,先刪除緩存,再去更新數(shù)據(jù)庫,再添加緩存 這樣的話即使緩存更新失敗了 緩存里面的數(shù)據(jù)也被刪了,如果刪除緩存都失敗的話,就不更新數(shù)據(jù)庫了,直接拋異常解決,這時候如果后面一個加入緩存失敗的話只是增加了一次查詢數(shù)據(jù)庫的操作而已(下一次查這個數(shù)據(jù)的時候把他加入緩存)
高并發(fā)下redis和數(shù)據(jù)庫不一致問題
如果這這兩個操作剛好在中間虛線部分那么緩存里面的數(shù)據(jù)和數(shù)據(jù)庫里面的數(shù)據(jù)就不一樣了,這個時候我們要解決這個問題就得引入分布式鎖
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://tiancixiong.blog.csdn.net/article/details/87940258