【发布时间】: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();
}
问题
即使缓存名称不同,该方法总是从缓存中返回列表,因为在生成键时方法级别没有区别。
可能的解决方案
我知道三种解决方案可能是:
- 更改方法名称
- 编写自定义 KeyGenerator
-
设置 Cache SpEL 以使用#root.target 例如:
@Cacheable(value="COCKTAILS", key="{#root.targetClass}") @Cacheable(value="INGREDIENTS", key="{#root.targetClass}")
问题
但是肯定有更好的方法吗?
【问题讨论】:
-
服务中的缓存数据将属于
@Cacheable注释指定的不同缓存区域,即它们将属于COCKTAILS和INGREDIENTS区域,因此即使它们的键相同,它们将被缓存在不同的缓存区域中。由于其他原因,您似乎没有得到预期的结果。尝试启用 Spring Cache 的日志记录以查看发生了什么:具有 TRACE 级别的 org.springframework.cache。
标签: java spring-boot spring-cache