Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache 2 different bean methods in same ehCache?

Say I have 2 different bean methods which I want to cache by EhCache:

@Component
public class StatService {

@Cacheable(value = "statCalc")
public int getMeth1(int param) {
    // LOGIC1
}

@Cacheable(value = "statCalc")
public int getMeth2(int param) {
    // LOGIC2
}
}

I want to reside them in same cache - ehcache.xml:

<cache name="statCalc"
       ...
/>

The problem is that cache key is generated by input parameters and not by method signature, thus getMeth2(1) can return value cached by getMeth1(1).

What is the easiest way to build key using method name?

P.S. Please, don't mention the fact that using same cache for different methods could be wrong, just help to solve this problem.

like image 452
corvax Avatar asked Apr 20 '16 10:04

corvax


People also ask

Is Ehcache distributed cache?

Answer. EhCache is a third party tool used to maintain cache across all the nodes in a clustered environment.

Is Ehcache in memory cache?

In this article, we will introduce Ehcache, a widely used, open-source Java-based cache. It features memory and disk stores, listeners, cache loaders, RESTful and SOAP APIs and other very useful features.

What is timeToLiveSeconds in Ehcache?

timeToLiveSeconds – The maximum number of seconds an element can exist in the cache regardless of use. The element expires at this limit and will no longer be returned from the cache. The default value is 0, which means no TTL eviction takes place (infinite lifetime).

How do I add CacheManager cache?

A new cache based on the default configuration can be added to a CacheManager very simply: manager. addCache(cacheName);


1 Answers

Spring Cache abstraction allows you to use SpeL to specify the cache key. For example you can use a method name , parameter values etc.

For example

@Component
public class StatService {

   @Cacheable(value="statCalc",key="#root.method.name.concat(':').concat(#param)")
   public int getMeth1(int param) {
      // LOGIC1
   }

   @Cacheable(value="statCalc",key="#root.method.name.concat(':').concat(#param)")
   public int getMeth2(int param) {
   // LOGIC2
   }
}

For the method call getMeth1(5) the key will be getMethod1:5 For method call getMethod1(0) key will be getMethod1:0

For method call getMeth2(3) the key will be getMethod2:3. This allows you to cache results for different parameters

like image 141
ekem chitsiga Avatar answered Oct 23 '22 18:10

ekem chitsiga