0
0
Spring Bootframework~5 mins

@Cacheable for read caching in Spring Boot

Choose your learning style9 modes available
Introduction

@Cacheable helps save time by storing data from slow methods so next time it can give the saved data quickly without running the method again.

When you have a method that fetches data from a database and the data does not change often.
When you want to reduce the number of times a slow or expensive method runs.
When you want to improve app speed by reusing previously fetched results.
When you want to avoid repeated calls to external services for the same data.
When you want to keep your app responsive by caching read-only data.
Syntax
Spring Boot
@Cacheable(value = "cacheName", key = "#key")
public ReturnType methodName(Parameters) {
    // method code
}

value is the name of the cache where data is stored.

key defines how to identify cached data uniquely, often using method parameters.

Examples
Caches the result of findBookById using the default key (method parameter).
Spring Boot
@Cacheable(value = "books")
public Book findBookById(Long id) {
    // fetch book from database
}
Uses the username parameter as the cache key explicitly.
Spring Boot
@Cacheable(value = "users", key = "#username")
public User getUser(String username) {
    // fetch user details
}
Creates a combined key from id and locale to cache localized product data.
Spring Boot
@Cacheable(value = "products", key = "#id + '-' + #locale")
public Product getProduct(Long id, String locale) {
    // fetch product with locale
}
Sample Program

This service method simulates a slow call by waiting 3 seconds. Using @Cacheable, the first call with an id will take time, but next calls with the same id return instantly from cache.

Spring Boot
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class BookService {

    @Cacheable(value = "books", key = "#id")
    public String findBookById(Long id) {
        simulateSlowService();
        return "Book " + id;
    }

    private void simulateSlowService() {
        try {
            Thread.sleep(3000); // simulate delay
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException(e);
        }
    }
}
OutputSuccess
Important Notes

Cache keys should uniquely identify the data to avoid wrong data returns.

Cached data stays until cache is cleared or expires, so use for mostly read-only data.

Make sure caching is enabled in your Spring Boot app with @EnableCaching annotation.

Summary

@Cacheable stores method results to speed up repeated calls.

Use it for slow or expensive read operations that return the same data for same inputs.

Define cache name and keys clearly to avoid confusion.