何时使用新的缓存名称?

4

在Ehcache中何时应该重用缓存,何时应该创建新的缓存呢?

示例1:

我有以下方法:

public Dog getBestDog(String name) {
    //Find the best dog with the provided name
}

public Dog getBestBrownDog(String name) {
    //Find the best brown dog with the provided name
}

对于给定的字符串(例如“rover”),这两种方法可能会返回不同的Dog对象。

我应该在两个方法上都注释@Cacheable(cacheName = "dogs"),还是应该将它们放在两个不同的缓存中,“bestDogs”和“bestBrownDogs”?

示例2:

我有以下方法:

public Dog getBestDogByName(String name) {
    //Find the best dog with the provided name
}

public Dog getBestDogByColour(String colour) {
    //Find the best dog with the provided colour
}

名称为"rover"和颜色为"doggy-colour"的狗可能是同一只狗。

我应该在两个不同的缓存中注解它们,'dogsByName'和'dogsByColour',还是都用@Cacheable(cacheName = "dogs")注解?

2个回答

3

可以使用不同的缓存来实现。您还可以使用相同的缓存,只需使用SpEL并设置不同的键即可,例如:

@Cacheable(cacheName = "dogs", key = "'name.'+#name")
public Dog getBestDogByName(String name) {
    //Find the best dog with the provided name
}

@Cacheable(cacheName = "dogs", key = "'colour.'+#colour")
public Dog getBestDogByColour(String colour) {
    //Find the best dog with the provided colour
}

这段代码会做一些聪明的事情吗?例如,如果同一个对象被两个不同的方法返回,它只会存储一份副本吗? - Brian Beckett
除非在ehcache中有配置的方法,否则它不会这样做。 - aweigold

3
每当您遇到同一键可能导致不同结果的情况时,您可能需要一个单独的缓存。
示例1: getBestDog(name) - 使用名称作为“best-dogs”缓存的键 getBestBrownDog(name) - 使用名称作为“best-brown-dogs”缓存的键
示例2: getBestDogByName(name) - 与示例1相同,使用名称作为“best-dogs”缓存的键 getBestDogByColour(colour) - 使用颜色作为“best-dogs-by-colour”缓存的键
这样就留下了3个缓存,“best-dogs”,“best-brown-dogs”,“best-dogs-by-colour”。
理论上,您可以合并“best-dogs”和“best-dogs-by-colour”...但是也许您有一只名为“red”的狗...那将是一个未考虑到的边缘情况。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接