Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java Spring boot cache

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?

like image 407
aarti gadge Avatar asked Mar 29 '26 19:03

aarti gadge


1 Answers

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.

like image 90
Dubas Avatar answered Mar 31 '26 11:03

Dubas