2012-02-11 41 views
3

什么时候应该在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 
} 

对于一个给定字符串(例如, “漫游者”),这两种方法可以返回不同的狗对象。

我应该用@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 
} 

名称 “漫游者” 和色彩 “狗色” 可以返回相同的狗。

我是否应该用@Cacheable(cacheName = "dogs")对它们进行注释,还是应该将它们放在两个不同的缓存中:'dogsByName'和'dogsByColour'?

回答

3

每当你有一个场景,相同的键可能导致不同的结果,那么你可能需要一个单独的缓存。

例1:

getBestDog(name) - 使用的名称从“最好的狗”缓存

getBestBrownDog(name)的关键 - 使用的名称从“最好的棕色狗的高速缓存中的关键

实施例2:

getBestDogByName(name) - 实施例1相同,使用的名称作为从 '最佳狗' 缓存键

getBestDogByColour(colour) - 使用颜色作为'最好的狗'颜色缓存的关键

这给你留下3个缓存,'最好的狗','最好的狗','最好的狗'颜色'

从理论上讲,你可以合并'最好的狗'和'最好的狗'颜色'......但也许你有一只叫做'红色'的狗......所以这将是一个不明的对于边缘情况。

3

使用不同的缓存可以工作。您也可以使用相同的缓存,只是通过规划环境地政司的东西,如使用不同的密钥进行设置如下:

@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 
} 
+0

这是否会做任何事情,聪明的一样,如果它是由不同的两种方法返回存储的对象只有一个副本钥匙? – 2012-02-13 17:09:30

+0

它不会,除非有办法在ehcache中配置它。 – aweigold 2012-02-13 17:26:59

相关问题