1
votes

I have java spring boot application. I want to use cache for frequently read data. For this i included the following dependencies in my jar

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>      
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

I have also used the @EnableCaching annotation

@EnableCaching 
public class SpringBootConfig {
public static void main(String[] args) throws Exception {
    SpringApplication.run(SpringBootConfig.class, args);    
  }
}

Used @Cacheable annotation with the function that return the data i want to cache

@Cacheable(value = "country",key = "'countryCache'+#countryCode")
private Country getCountry(String countryCode) {
    return new Country(countryCode);
}

But I am still not able to cache the data. Is there anything that i am missing?

3

3 Answers

2
votes

did you already had a look in the Getting Started Guide for Caching Data?

There is a paragraph which will explain why the cache isn't working in your code.

The @EnableCaching annotation triggers a post-processor that inspects every Spring bean for the presence of caching annotations on public methods. If such an annotation is found, a proxy is automatically created to intercept the method call and handle the caching behavior accordingly.

Because your getCountry Method is private the caching won't work. Maybe it is reasonable for you to cache the result of the calling method?

1
votes

The annotation @Cacheable is only available for public exposed method that are allowed to be intercepter. But you could get the "CacheManager" services and use it in your code to handle internally the cache in the privated methods if required. But only to solve some "special" problems the usual way is to annotate the public methods.

Also if you use only the starter you are using only the basic and poor implementation of Spring, a simple memory cache.

Think about how your application will work (single app, distributed app, short/long amount of data cached,...) and the memory consumption to add a dependency of any of the supported cache managers like ehCache, Hazelcast,Caffeine,... that meets your requirements and improves your cache performance.

1
votes

Only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual cache interception at runtime even if the invoked method is marked with @Cacheable.

Also, I would recommend using Ehcache implementation with spring boot, which allows you to do conditional caching. check this post