Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Cachable on methods without input parameters?

I'm having a problem with @org.springframework.cache.annotation.Cachable annotation:

@Bean
public ConcurrentMapCache cache() {
    return new ConcurrentMapCache(CACHE);
}

@Cacheable(CACHE)
public String getApi() {
    return "api";
}

@Cacheable(CACHE)
public String getUrl() {
    return "url";
}

usage:

assertEquals("api", service.getApi()); //OK
assertEquals("url", service.getUrl()); //FAILURE. this returns also "api"

So, why does @Cachable not create a cache result by method name if method signature does not contain any input parameters?

like image 311
membersound Avatar asked Feb 20 '18 15:02

membersound


2 Answers

Try this

@Cacheable(value = CACHE, key = "#root.method.name")

You need to tell spring to use method name as key. You can use SPEL for this. Here is the doc with various other options.

like image 161
pvpkiran Avatar answered Oct 30 '22 06:10

pvpkiran


You can use two cache with different name:

@Bean
public ConcurrentMapCache cache() {
    return new ConcurrentMapCache(CACHE_API, CACHE_URL);
}
@Cacheable(CACHE_API)
public String getApi() {
    return "api";
}

@Cacheable(CACHE_URL)
public String getUrl() {
    return "url";
}
like image 26
akasha Avatar answered Oct 30 '22 06:10

akasha