不同服务中相同方法的Spring @Cacheable注解 [英] Spring @Cacheable annotation for same method in different service

查看:34
本文介绍了不同服务中相同方法的Spring @Cacheable注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经按照以下 文章:

我有两个不同的服务来获取对象列表:

What I have is two different services that get a list of objects:

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

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

    return "index";
}

注意:方法名称和签名是相同的(即 list() ),但它们都有不同的缓存名称,例如:

Note: that the method name and signature is the same (i.e. list() ) but they both have different cache names as such:

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

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

问题

即使缓存名称不同,方法也总是从缓存中返回列表,因为在生成键时在方法级别没有区别.

Even thou the cache name is different the method is always returning the list from the cache as there is no distinction at method level when generating the keys.

可能的解决方案

我知道三种解决方案可能是:

I know three solutions could be:

  1. 更改方法名称
  2. 编写自定义密钥生成器
  3. 设置缓存 SpEL 以使用 #root.target 例如:

  1. Change the method name
  2. Write a custom KeyGenerator
  3. Set Cache SpEL to make use of #root.target such as:

@Cacheable(value="鸡尾酒", key="{#root.targetClass}")@Cacheable(value="INGREDIENTS", key="{#root.targetClass}")

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

问题

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

But surly there must be a better way or not?

推荐答案

您关注的文章中存在问题.创建CacheManager bean 时,需要调用cacheManager.setUsePrefix(true);,然后才调用缓存名称​​COCKTAILSINGREDIENTS 将用作 Redis 缓存密钥鉴别器.

There is an issue in the article you've followed. When creating your CacheManager bean, you need to invoke cacheManager.setUsePrefix(true);, only then the cache names COCKTAILS and INGREDIENTS will be used as Redis cache key discriminator.

以下是您应该如何声明缓存管理器 bean:

Here is how you should declare your cache manager 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 @Cacheable注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆