top of page
Writer's pictureSudha valli

Spring Boot Caching




Caching is a mechanism using which, an application’s performance can be enhanced easily. A database fetch operation is time consuming and a costly effort. Caching avoids frequent database hits and relieves the database load. It is advisable to cache only data that is frequently needed.


Cache needs maintenance, in the sense, we need to make sure the cached data always reflects and matches the database. Data mismatch can lead to serious consequences.


Spring boot has in-built support for caching and can be achieved with its autoconfiguration feature. Let's understand how to implement in-memory caching in a spring boot application with the help of annotations.

Cache Dependency

In the spring boot application, add the spring-boot-starter-cache starter package dependency for caching in pom.xml

@EnableCaching


We need to enable caching by including the @EnableCaching annotation in one of the configuration files. It can be the application’s boot class.



@Cacheable


It is time to annotate the methods that need to be cached. Usually, caching is best achieved by annotating the service class methods where the application’s business logic resides.


What exactly does the @Cacheable annotation does? This method-level annotation lets the spring boot know that the cache with the name “employees” to be first searched with the given 'empId' before invoking the method.



The ‘key’ attribute lets you specify an id for each entry into the cache. If a key is not specified, spring uses a combination of the method parameters as key to uniquely identify the cached data.

In the above example, the ‘getEmployeeById( ) will first looks for the employee in the ‘employees’ cache with the key ‘empId’. If the required info is not available in the cache, the method gets executed to retrieve the employee info from database.

@CachePut


This annotation is used to add or update the cache without interfering with the method execution.



The addEmployee( ) executes and adds the result to the ‘employees’ cache.



In some cases, if the method parameter is an object and we want to mention the key as one of its member variables, we can specify the key as follows.



The key difference between @Cacheable and @CachePut annotation is that the @Cacheable skips the method execution if results are available in cache, while @CachePut runs the method and updates the results into the cache.

@CacheEvict

This annotation is used to remove an entry from cache.

We can also remove all the entries from cache by mentioning ‘allEntries=true’ in @CacheEvict



Over time, Cache can grow extremely large and unmanageable. To avoid such situation, it needs to be cleaned by deleting the unused data. This annotation helps to clean the unnecessary data from cache.


43 views

Recent Posts

See All
bottom of page