【问题标题】:Spring @Cacheable annotation for same method in different service不同服务中相同方法的Spring @Cacheable注解
【发布时间】:2017-12-27 14:15:21
【问题描述】:

我已经按照以下article 在 Spring Boot 应用程序中实现了标准的 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}")

问题

但是肯定有更好的方法吗?

【问题讨论】:

  • 服务中的缓存数据将属于@Cacheable注释指定的不同缓存区域,即它们将属于COCKTAILSINGREDIENTS区域,因此即使它们的键相同,它们将被缓存在不同的缓存区域中。由于其他原因,您似乎没有得到预期的结果。尝试启用 Spring Cache 的日志记录以查看发生了什么:具有 TRACE 级别的 org.springframework.cache

标签: java spring-boot spring-cache


【解决方案1】:

您关注的文章中存在问题。创建 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;
}

【讨论】:

  • 显然在处理其他缓存解决方案时,Spring 的 CacheManger 通常包含一个由单独的缓存支持的缓存映射(每个实现类似映射的功能)实现。使用默认的 RedisCacheManager 配置,情况并非如此。根据对 RedisCacheManager 的 javadoc 评论,不清楚这是一个错误还是只是不完整的文档。 “……默认情况下,通过附加前缀(充当命名空间)来保存键。” javacodegeeks.com/2013/02/caching-with-spring-data-redis.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 2019-01-30
  • 2013-06-26
相关资源
最近更新 更多