Google News
logo
Java Spring Boot - Interview Questions
How to implement Caching in Spring Boot?
Caching is a mechanism that helps in reducing roundtrip calls to Database, REST service, files, etc. Performance under heavy load is a key feature expected from any modern web and mobile application, hence caching is really vital to enhance the speed of fetching data.
 
Spring Boot provides a starter project for caching “spring-boot-starter-cache”, adding this to an application brings in all the dependencies to enable JSR-107 (JCACHE - Java Temporary Caching API) and Spring caching annotations.
 
In order to enable caching in a Spring Boot application, we need to add @EnableCaching to the required configuration class. This will automatically configure a suitable CacheManager to serve as a provider for the cache.
 
Example :
 
@Configuration
@EnableCaching
public class CachingConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("addresses");
}
}
 
Now to enable caching, we need to add a @Cacheable annotation to the methods where we want to cache the data.
 
@Cacheable("addresses")
public String getAddress(Customer customer) {...}

 

Advertisement