When should I reuse a cache in Ehcache and when should I create a new one?
Example 1:
I have the following methods:
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
}
For a given String (e.g. “rover”), these two methods could return a different Dog object.
Should I annotate them both with @Cacheable(cacheName = "dogs") or should I put them in two different caches, “bestDogs” and “bestBrownDogs”?
Example 2:
I have the following methods:
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
}
Name “rover” and colour “doggy-colour” could return the same Dog.
Should I annotate them both with @Cacheable(cacheName = "dogs") or should I put them in two different caches, ‘dogsByName’ and ‘dogsByColour’?
Whenever you have a scenario where the same key can result in different results, then you probably want a separate cache.
Example 1:
getBestDog(name)– use the name as the key from ‘best-dogs’ cachegetBestBrownDog(name)– use the name as the key from ‘best-brown-dogs’ cacheExample 2:
getBestDogByName(name)– same as example 1, use name as key from ‘best-dogs’ cachegetBestDogByColour(colour)– use colour as key from ‘best-dogs-by-colour’ cacheWhich leaves you with 3 caches, ‘best-dogs’, ‘best-brown-dogs’, ‘best-dogs-by-colour’
In theory, you could merge ‘best-dogs’ and ‘best-dogs-by-colour’… but maybe you have a dog who is called ‘red’.. so that would be an unaccounted for edge case.