簡體   English   中英

Spring @Cacheable注解用於不同服務中的相同方法

[英]Spring @Cacheable annotation for same method in different service

我已經按照以下文章在Spring啟動應用程序中實現了標准的redis緩存模板:

我所擁有的是兩種不同的服務,它們可以獲取對象列表:

@RequestMapping("/admin/test/list")
public String testCache() {

    List<Cocktail> cocktails = cocktailsService.list();
    List<Ingredient> ingredients = ingredientsService.list();

    return "index";
}

注意:方法名稱和簽名是相同的(即list() ),但是它們都具有不同的緩存名稱,例如:

// CocktailService
@Cacheable(value = “COCKTAILS”)
public List<Cocktail> list() {
    return repository.findAll();
}

// IngredientsService
@Cacheable(value = “INGREDIENTS”)
public List<Ingredient> list() {
    return repository.findAll();
}

問題

即使高速緩存名稱不同,該方法也總是從高速緩存返回列表,因為在生成鍵時在方法級別沒有區別。

可能的解決方案

我知道三種解決方案可能是:

  1. 更改方法名稱
  2. 編寫自定義KeyGenerator
  3. 將Cache SpEL設置為使用#root.target,例如:

    @Cacheable(value =“ COCKTAILS”,key =“ {#root.targetClass}”)@Cacheable(value =“ INGREDIENTS”,key =“ {#root.targetClass}”)

但是,一定有更好的辦法嗎?

您所關注的文章中有一個問題。 創建CacheManager bean時,需要調用cacheManager.setUsePrefix(true); ,則只有緩存名稱COCKTAILSINGREDIENTS才用作Redis緩存密鑰鑒別符。

這是您應該如何聲明緩存管理器bean的方法:

@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);

    // Number of seconds before expiration. Defaults to unlimited (0)
    cacheManager.setDefaultExpiration(300);
    cacheManager.setUsePrefix(true);
    return cacheManager;
}

暫無
暫無

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

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