簡體   English   中英

為 Spring 的 @Cacheable 注釋定義鍵的最佳方法是什么

[英]What is the best way of defining key for @Cacheable annotation for Spring

如果我為沒有任何參數的方法定義 ehcache。

但是在我的用例中,我需要通過它的鍵來訪問我構建的緩存。

所以請為我提供更好的分配密鑰的方法。

以下是我的代碼:

@Override
@Cacheable(value = "cacheName", key = "cacheKey")
public List<String> getCacheMethod() throws Exception{

PS 當我嘗試從其他地方訪問此方法時出現以下錯誤。

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): 在“org.springframework.cache.interceptor.CacheExpressionRootObject”類型的對象上找不到字段或屬性“cacheKey”

該方法沒有參數,因此無法使用參數/參數作為默認鍵,並且您不能使用“靜態文本”作為鍵,您可以執行以下操作:

聲明以下內容

public static final String KEY = "cacheKey";
  • 必須public
  • 必須是staticfinal

然后

@Override
@Cacheable(value = "cacheName", key = "#root.target.KEY")
public List<String> getCacheMethod() throws Exception{

完畢

在簡單的情況下,您可以使用更簡單的方法: @Cacheable(key = "#root.methodName") ,並且鍵將等於帶注釋的方法的名稱

請看一下這個spring 文檔

鍵是指你的方法的參數,你有SpelEvaluationException因為cachekey不在你的方法參數中。

您可以在鍵中使用單引號解決這個問題,使其再次成為字符串。

@Cacheable(value= CACHE_NAME.PRODUCT_CATLOG, key=" 'products' ")
    public List<Product> findAll() {
        return StreamSupport.stream(productRepository.findAll().spliterator(),false).collect(Collectors.toList());
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM