Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring cache constant as a key

Tags:

spring-cache

As part of my code I have a method with empty parameters. For e..g,

public MasterData fetchMasterData() {
// DO something.
}

I want to add a @Cacheable with key as 'masterdata'. I tried the following, but it looks for a bean named 'masterdata'. I tried @Cacheable(cache="master", key="masterdata")

If I leave the key attribute, I know it takes as empty key. But I want to explicitly give a constant as key.

Is there a way to do that?

like image 877
Poorna Subhash Avatar asked Feb 17 '15 08:02

Poorna Subhash


People also ask

How do I keep my spring boot caching?

The simplest way to enable caching behavior for a method is to mark it with @Cacheable and parameterize it with the name of the cache where the results would be stored. It provides a parameter called allEntries that evicts all entries rather than one entry based on the key.

What is key in cache in 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.

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.

How does @cachable work?

As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method.


1 Answers

The key attribute is a SpEL expression so if you want the key to be masterdata you would write something like this

@Cacheable(cache="master", key="'masterdata'")
public MasterData fetchMasterData() { ... }
like image 171
Stephane Nicoll Avatar answered Oct 16 '22 22:10

Stephane Nicoll