简体   繁体   中英

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.

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM