使用@CachePut?更新數(shù)據(jù)庫和更新緩存
關(guān)于更新緩存 ,要注意兩點
1、@Cacheable的key
要和@CachePut 的key一致
比如:
@Cacheable(key = "'userCache'") //緩存,
public Uuser findByEmail(String email) {
System.err.println("執(zhí)行這里,說明緩存中讀取不到數(shù)據(jù),直接讀取數(shù)據(jù)庫....");
return redisMapper.findByEmail(email);
}
@CachePut(key = "'userCache'") //userCache要加‘'單引號,表示這是一個字符串
public Uuser updateSelf(String nickname, String email) {
System.err.println("執(zhí)行這里,更新數(shù)據(jù)庫,更新緩存....");
uuserMapper.updateSelf(nickname, email);
Uuser uuser = redisMapper.findByEmail(email);
return uuser;
}
2、@CachePut的返回值
要和@Cacheable的返回值一樣
如果@Cacheable 返回的是一個對象,@CachePut 返回也要是對象,否則會報類型轉(zhuǎn)換異常,如上代碼 返回的都是 Uuser.
緩存的CachePut沖突Cacheable
CachePut 跟 Cacheable放在一起, Cacheable的效果就跟 CachePut 一樣的,每次都會去查數(shù)據(jù)庫,雖然有緩存。
/**
*
* @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 接口類參數(shù)。用#參數(shù)名無效。 只能用#p0, #p1
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用Java的Graphics類進(jìn)行繪圖的方法詳解
這篇文章主要介紹了使用Java的Graphics類進(jìn)行繪圖的方法,是Java的GUI編程的基礎(chǔ),需要的朋友可以參考下2015-10-10
使用IDEA創(chuàng)建java項目的步驟詳解(hello word)
這篇文章主要介紹了使用IDEA創(chuàng)建java項目的步驟詳解(hello word),本文分步驟通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
java判斷l(xiāng)ist不為空的實現(xiàn),和限制條數(shù)不要在一起寫
這篇文章主要介紹了java判斷l(xiāng)ist不為空的實現(xiàn),和限制條數(shù)不要在一起寫。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
SpringBoot中數(shù)據(jù)傳輸對象(DTO)的實現(xiàn)
本文主要介紹了SpringBoot中數(shù)據(jù)傳輸對象(DTO)的實現(xiàn),包括了手動創(chuàng)建DTO、使用ModelMapper和Lombok創(chuàng)建DTO的示例,具有一定的參考價值,感興趣的可以了解一下2024-07-07

