溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用@CachePut更新數(shù)據(jù)庫和更新緩存

發(fā)布時間:2021-12-28 10:40:03 來源:億速云 閱讀:382 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下如何使用@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

以上是“如何使用@CachePut更新數(shù)據(jù)庫和更新緩存”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI