redis在spring集成下key與value的使用方法

假設一切都已經配置妥當。

Spring緩存註解@Cache,@CachePut , @CacheEvict,@CacheConfig使用的使用方法參照: http://blog.csdn.net/sanjay_f/article/details/47372967

@Cacheable(value=”testcache”,key=”#userName”) 

使用的時候 value與key組成了唯一標識來標識一個緩存,key可以不指定。
如果key不指定的話,參數會作爲key與value進行組合對應一個緩存。
可以理解爲,如果key寫死的話,那麼這個方法的緩存就確定了,無論傳什麼值來,返回的都是這個緩存。
如果key不指定,那麼每次傳不同的參數,value就會與新參數組合爲一個新的標識,指向新的緩存。
key也可以指向參數對象中的某個值。
如果參數是一個string 那麼key可以不寫了
如果參數是一個實體 那麼key可以寫爲實體的id

其實可以理解爲,value是一個組,我們可以把一個接口裏面的所有value都定義爲同一,然後key不同,或者說key以參數加個後綴區分。

這個value與key,如果對應map的話,其實是map中的key 緩存是map中的value

   @Cacheable(value= "customLikeName", key="#test")

test爲function的參數,String類型

     @Cacheable(value= "customLikeName", key="#orgCustom.getId()")

orgCustom爲一個實體,非常實用

    @Cacheable(value= "customLikeName", key="'jerry'")

key寫死,沒什麼卵用

@Cacheable(value="andCache",key="#userId + 'findById'")    
public SystemUser findById(String userId) {    
    SystemUser user = (SystemUser) dao.findById(SystemUser.class, userId);          
    return user ;           
}  

這種寫法可以應對key爲部分參數的情況

@Cacheable(value = CacheConstant.newsCache)
    public String loadNewsList(DeNewsTitle deNewsTitleVo, @PathVariable("posId") int posId)

這時緩存是不起作用的
之所以不走緩存,是因爲每次創建了不同的 DeNewsTitle 對象,緩存的 key 生成策略認爲不是同一個參數。解決方法是爲 DeNewsTitle 對象添加 equals() 和 hashCode() 實現即可

關於equals和hashCode方法,參見: http://chroya.iteye.com/blog/803972

以上 僅做參考記錄

附錄:
關於@CacheConfig的使用:
Using @CacheConfig
@CacheConfig annotation is used at class level to share common cache related settings. All the methods of the class annotated with @Cacheable gets a common cache related settings provided by @CacheConfig. The attributes of @CacheConfig are cacheNames, cacheManager, cacheResolver and keyGenerator. We can override the class level cache related setting for a method using attributes of @Cacheable. Find a class annotated with @CacheConfig being used in our demo.

Student.java

package com.concretepage;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
@CacheConfig(cacheNames="mycacheone")
public class Student {
   @Cacheable
   public String getStudentName(int stdId) {
    System.out.println("execute getStudentName method...");
    if (stdId == 1) {
        return "Ramesh";
    } else {
        return "Mahesh";
    }
   }
   @Cacheable(value = "mycachetwo")
   public String getCity(int cityId) {
    System.out.println("execute getCity method...");
    if (cityId == 1) {
        return "Varanasi";
    } else {
        return "Allahabad";
    }
   }
} 
發佈了24 篇原創文章 · 獲贊 31 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章