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.
Answer. EhCache is a third party tool used to maintain cache across all the nodes in a clustered environment.
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.
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).
A new cache based on the default configuration can be added to a CacheManager very simply: manager. addCache(cacheName);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With