Spring Boot @Cacheable Example

1. Introduction

This blog post will demonstrate the use of the @Cacheable annotation in a Spring Boot application.

Key Points:

1. The @Cacheable annotation indicates that the result of a method should be cached.

2. It can dramatically improve performance by avoiding repeated method calls for the same data.

3. This annotation is flexible, allowing for the specification of cache names, conditionals, and key generators.

4. Proper use of @Cacheable requires understanding the underlying cache manager and store configuration.

5. Caching is ideal for methods that retrieve data that doesn't change often and is expensive to fetch.

2. Implementation Steps

1. Include the cache abstraction dependency in your Spring Boot project.

2. Configure a cache manager within your application context.

3. Annotate methods with @Cacheable to indicate that their results should be cached.

4. Specify the cache name and, optionally, a key within the @Cacheable annotation.

5. Test the caching behavior to ensure that the method’s execution is being cached.

3. Implementation Example

// Step 1: Include the cache starter dependency in your build configuration file (Maven or Gradle)
// For Maven, add the following to your pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>


// Step 2: Configure your cache manager in a configuration class
@Configuration
@EnableCaching
public class CacheConfig {
    // Define a cache manager bean if necessary
}

// Step 3: Annotate service method to enable caching of its results
@Service
public class DataService {

    // This method's response will be cached under the 'books' cache
    @Cacheable(value = "books", key = "#isbn")
    public Book findBookByISBN(String isbn) {
        // Simulate slow service call
        try {
            Thread.sleep(3000); // This represents a heavy resource-intensive operation
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return new Book(isbn, "Some book title");
    }
}

// Step 4: Create a simple model class representing a Book
public class Book {
    private String isbn;
    private String title;

    // Constructor, getters and setters
}

// Step 5: Include caching annotations in your main application or a configuration class
@SpringBootApplication
@EnableCaching
public class CachingApplication {
    public static void main(String[] args) {
        SpringApplication.run(CachingApplication.class, args);
    }
}

Output:

// No explicit output here; however, the first call to findBookByISBN(String isbn) will take ~3000ms,
// while subsequent calls with the same isbn will return almost instantaneously from the cache.

Explanation:

1. @EnableCaching: This annotation triggers a post-processor that inspects every Spring bean for the presence of caching annotations on public methods.

2. @Cacheable: This annotation marks the method to cache its results. The value attribute specifies the cache name and the key attribute defines the unique key under which the results are stored in the cache.

3. value = "books": This indicates the name of the cache where the results are stored.

4. key = "#isbn": The SpEL expression for the key that results in using the method's ISBN argument as the cache key.

5. Cache Operation: When findBookByISBN is called, the method's execution is cached, and subsequent calls with the same ISBN will fetch the result from the cache, avoiding the need to execute the method body again.


Comments