Thursday, June 8, 2023

Spring caching

<<This document is for my own reference.  It helps me to remember these theories in the future. >>


First, we need to add the annotation "@EnableCaching" to the main method of the project.



The reason for using caching is to improve the system's performance. If you have saved data in the database and need to query data, you have to retrieve those values from the database each time request comes in. This could be a resource and time-consuming task. So the solution we have is, caching those data locally and passing it to the consumer if available in the local storage. 

We have to be very careful when we use this caching mechanism. Because, if we update/delete one value in the table we have to use specific annotations for those methods. Otherwise, cached data doesn't update and the consumer receives incorrect data.

Follow as below when retrieving data from the database. It caches all retrieved data.

According to the above sample code, name of the cache would be "books" and key would be "id". When you trigger this method, it first checks the key is exist in the "books" cache and if available, it doesn't execute the rest of the code.

How to update a value in the cache?

    







When you invoke the update method, specific cached values also get updated. "@CachePut" handles this task. Unlike in the "@Cacheable" annotation, this executes the rest of the code. 

How to delete a value in the cache?







"@CacheEvict" annotation takes care of removing existing cached values. If you don't use this annotation, cached values don't remove even it removed from the database.



No comments:

Post a Comment