Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of defining key for @Cacheable annotation for Spring

If I am defining a ehcache for a method which doesn't have any parameter.

But in my use case I needs to access the my built cache through it's key.

So please provide me the better way of assigning key on it.

Follow is my code:

@Override
@Cacheable(value = "cacheName", key = "cacheKey")
public List<String> getCacheMethod() throws Exception{

P.S. I am getting the following error when I am trying to access this method from somewhere else.

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'cacheKey' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject'

like image 342
BITSSANDESH Avatar asked Aug 02 '14 12:08

BITSSANDESH


People also ask

What is key in @cacheable Spring boot?

Any data stored in a cache requires a key for its speedy retrieval. Spring, by default, creates caching keys using the annotated method's signature as demonstrated by the code above. You can override this using @Cacheable's second parameter: key. To define a custom key you use a SpEL expression.

How does @cacheable work in Spring?

@CacheableThis method-level annotation lets Spring Boot know that the return value of the annotated method can be cached. Each time a method marked with this @Cacheable is called, the caching behavior will be applied.

What does @cacheable annotation do?

Annotation Type Cacheable. Annotation indicating that the result of invoking a method (or all methods in a class) can be cached. Each time an advised method is invoked, caching behavior will be applied, checking whether the method has been already invoked for the given arguments.

What is cacheable key?

The cache key is the unique identifier for an object in the cache. Each object in the cache has a unique cache key. A cache hit occurs when a viewer request generates the same cache key as a prior request, and the object for that cache key is in the edge location's cache and valid.


2 Answers

The method has no parameter, therefore there is no a way to use a parameter/argument as a default key, and you can't use "static text" as a Key, you could do the following:

Declare the following

public static final String KEY = "cacheKey";
  • must be public
  • must be static and final

Then

@Override
@Cacheable(value = "cacheName", key = "#root.target.KEY")
public List<String> getCacheMethod() throws Exception{

Done

like image 176
Manuel Jordan Avatar answered Nov 15 '22 06:11

Manuel Jordan


In simple cases you can use an easier way: @Cacheable(key = "#root.methodName"), and the key would be equal to annotated method's name

like image 33
Nikolai Shevchenko Avatar answered Nov 15 '22 05:11

Nikolai Shevchenko