0
0
Spring Bootframework~5 mins

Cache key strategies in Spring Boot

Choose your learning style9 modes available
Introduction

Cache keys help store and find data quickly in a cache. Good keys make your app faster and avoid mistakes.

When you want to speed up repeated data fetching in your Spring Boot app.
When you need to avoid recalculating expensive results multiple times.
When you want to share cached data safely between different users or requests.
When you want to control how cached data is stored and retrieved.
When you want to avoid cache conflicts or wrong data being returned.
Syntax
Spring Boot
@Cacheable(value = "cacheName", key = "#keyExpression")
Use SpEL (Spring Expression Language) inside the key attribute to build custom keys.
If you don't specify a key, Spring uses all method parameters by default.
Examples
Cache uses the book's ISBN as the key.
Spring Boot
@Cacheable(value = "books", key = "#isbn")
public Book findBook(String isbn) { ... }
Uses the user's id property as the cache key.
Spring Boot
@Cacheable(value = "users", key = "#user.id")
public User getUser(User user) { ... }
Combines method name and id to create a unique key.
Spring Boot
@Cacheable(value = "products", key = "#root.methodName + '_' + #id")
public Product getProduct(Long id) { ... }
No key specified, so all parameters (orderId) are used as the key.
Spring Boot
@Cacheable(value = "orders")
public Order getOrder(Long orderId) { ... }
Sample Program

This service method caches books by their ISBN. The first call waits 1 second, later calls 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 = "#isbn")
    public String findBook(String isbn) {
        // Simulate slow service
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "Book with ISBN: " + isbn;
    }
}
OutputSuccess
Important Notes

Always choose keys that uniquely identify the cached data to avoid wrong cache hits.

Use simple keys like IDs or combine multiple parameters if needed.

Remember that complex keys can slow down cache lookup.

Summary

Cache keys help find cached data fast and correctly.

Use Spring Expression Language (SpEL) to customize keys.

Pick keys that uniquely identify the data you want to cache.