使用@CachePut?更新數據庫和更新緩存
更新時間:2021年12月28日 08:45:06 作者:王某人i
這篇文章主要介紹了使用@CachePut?更新數據庫和更新緩存方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
關于更新緩存 ,要注意兩點
1、@Cacheable的key
要和@CachePut 的key一致
比如:
@Cacheable(key = "'userCache'") //緩存,
public Uuser findByEmail(String email) {
System.err.println("執(zhí)行這里,說明緩存中讀取不到數據,直接讀取數據庫....");
return redisMapper.findByEmail(email);
}
@CachePut(key = "'userCache'") //userCache要加‘'單引號,表示這是一個字符串
public Uuser updateSelf(String nickname, String email) {
System.err.println("執(zhí)行這里,更新數據庫,更新緩存....");
uuserMapper.updateSelf(nickname, email);
Uuser uuser = redisMapper.findByEmail(email);
return uuser;
}
2、@CachePut的返回值
要和@Cacheable的返回值一樣
如果@Cacheable 返回的是一個對象,@CachePut 返回也要是對象,否則會報類型轉換異常,如上代碼 返回的都是 Uuser.
緩存的CachePut沖突Cacheable
CachePut 跟 Cacheable放在一起, Cacheable的效果就跟 CachePut 一樣的,每次都會去查數據庫,雖然有緩存。
/**
*
* @param id
* @return
*/
@Caching( put = {
@CachePut(key = "T(cn.a.b.constant.RedisKey).OPEN_MEDIUM_INFO + #result.mediumBankCard", unless="#result.mediumBankCard==null or #result.status !='2'"),
@CachePut(key = "T(a.b.c.constant.RedisKey).ACCOUNT_CODE + #result.accountCode", unless="!{'0','1','2','3'}.contains(#result.mediumStatus)"),
@CachePut(key = "T(a.b.c.constant.RedisKey).CERT_NO+ #result.certNo", unless="#result.certNo==null or !{'0','1','2','3'}.contains(#result.status)")
}
, cacheable = {@Cacheable(key="T(a.b.c.constant.RedisKey).ID + #id")}
)
public XXXInfo selectByPrimaryKey(Long id){
return mapper.selectByPrimaryKey(id);
}
可以分解成兩個
Service.java
/**
*
* @param id
* @return
*/
@Caching( put = {
@CachePut(key = "T(cn.a.b.constant.RedisKey).OPEN_MEDIUM_INFO + #result.mediumBankCard", unless="#result.mediumBankCard==null or #result.status !='2'"),
@CachePut(key = "T(a.b.c.constant.RedisKey).ACCOUNT_CODE + #result.accountCode", unless="!{'0','1','2','3'}.contains(#result.mediumStatus)"),
@CachePut(key = "T(a.b.c.constant.RedisKey).CERT_NO+ #result.certNo", unless="#result.certNo==null or !{'0','1','2','3'}.contains(#result.status)")
}
)
public XXXInfo selectByPrimaryKey(Long id){
return mapper.selectByPrimaryKey(id);
}
Mapper.java
{
@Cacheable(key="T(a.b.c.constant.RedisKey).ID + #p0")
XXXXInfo selectByPrimaryKey(Long id);
}
mybatis 接口類參數。用#參數名無效。 只能用#p0, #p1
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
使用IDEA創(chuàng)建java項目的步驟詳解(hello word)
這篇文章主要介紹了使用IDEA創(chuàng)建java項目的步驟詳解(hello word),本文分步驟通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
java判斷l(xiāng)ist不為空的實現,和限制條數不要在一起寫
這篇文章主要介紹了java判斷l(xiāng)ist不為空的實現,和限制條數不要在一起寫。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01

