Search code examples
javaspringehcache

Spring MVC - Ehcache best practices


I have a question about best pratices using spring and ehCache.

For example if I have two methods annotated with @Cacheable that are using the same parameter value, ehcache will return the latest cache value.

@Cacheable(value="imagesCache",key="#id_image")
public Image getUserImage(id_image){ //stuff }

//and 

@Cacheable(value="imagesCache",key="#id_image")
public Image getProductImage(id_image){ //stuff }

If I first call getUserImage(10) and then getProductImage(10), ehcache will return same value for both methods because they have the same key. I tought that ehcache, indexes the cache value using key and method name, so that if two methods have the same #key(10 in my example) it will look at the method name.

I know that the easiest solution is to create two caches ("userImagesCache" and "productImagesCache") but in this context I want to avoid this.

How to solve this?

Thank you.


Solution

  • According to @Cacheable javadoc key is a SpEL expression, so you might to make smth like that:

    @Cacheable(value="imagesCache",key="'user' + #id_image")
    public Image getUserImage(id_image){ //stuff }
    
    //and 
    
    @Cacheable(value="imagesCache",key="'product' + #id_image")
    public Image getProductImage(id_image){ //stuff }