How to cache data in Springboot application

To cache data in a Spring Boot application, you can use the @Cacheable annotation on a method. When the method is called, the data returned by the method will be stored in a cache. Subsequent calls to the method will return the cached data, rather than executing the method again, until the cache is evicted or expired.

In the following example, @EnableCaching annotation enables the cache mechanism.

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

Here is an example of how to use the @Cacheable annotation:

@Cacheable(value = "users", key = "#userId")
public User getUserById(Long userId) {
    // This method will be called only on the first invocation,
    // and the result will be cached.
    return userRepository.findById(userId);
}


In this example, the getUserById() method will be called and the result will be stored in a cache named "users" with the key being the userId parameter. Subsequent calls to the getUserById() method with the same userId will return the cached result, rather than executing the method again. You can also use the @CacheEvict annotation to evict data from the cache. For example:

@CacheEvict(value = "users", key = "#userId")
public void updateUser(Long userId, User user) {
    // This method will remove the user with the specified ID from the cache
    // before updating the user in the database.
    userRepository.save(user);
}

This will remove the user with the specified userId from the "users" cache before updating the user in the database. There are many other features and configuration options available for caching in Spring Boot, including support for different cache providers and the ability to specify cache expiration policies. I hope this helps! Please share your queries/feedbacks in comments section.

Comments

Popular posts from this blog

How to Run Python Script in PM2 Server

Handling Performance Bottlenecks in Spring Applications

Retry in SprinBoot Application