Learn Spring Β· 12/15

Caching for Performance

8 min read

Caching for Performance πŸš€

Welcome, intrepid Spring developer! Today, we're diving into the wonderful world of caching. Ever felt like your application is moving at the speed of a sloth on a lazy Sunday? Caching might just be the espresso shot it needs. We'll explore how to make your Spring applications faster and more efficient by storing frequently accessed data in a temporary, high-speed storage layer.


1. Why Cache? Understanding the Spring Cache Abstraction πŸ€”

The Problem: Imagine you're building an e-commerce application. Every time a user visits the homepage, your application has to fetch the list of best-selling products from the database. This involves a network call, disk I/O, and database processing. Now, what happens when a thousand users visit the homepage at the same time? Your database will be working overtime, and your application's response time will plummet. This is not ideal for user experience or for the sanity of your database administrator.

The Solution: Caching!

Caching is the process of storing copies of data in a temporary storage location (a cache) so that they can be accessed more quickly. Instead of repeatedly fetching the same data from a slow backend (like a database or a remote service), we can retrieve it from our high-speed cache.

Spring Cache Abstraction: The "One Ring to Rule Them All"

Before Spring introduced its caching abstraction, developers had to manually implement caching logic. This often meant tightly coupling the application code with a specific caching library. If you ever wanted to switch from one caching provider to another, you'd be in for a world of pain, rewriting significant chunks of your code.

The Spring Cache Abstraction provides a set of annotations that allow you to declaratively add caching to your methods. This means you can add caching behavior without modifying the method's implementation. It acts as a facade, decoupling your code from the underlying cache implementation. You can switch from an in-memory cache to a distributed cache like Redis with just a few configuration changes, without touching your business logic. It's like having a universal remote for all your caching needs.

Under the hood, Spring uses Aspect-Oriented Programming (AOP) proxies. When you annotate a method, Spring creates a proxy that intercepts calls to that method. Before the method is executed, the proxy checks the cache. If the data is found, it's returned directly without executing the method. If not, the method is executed, and its result is stored in the cache before being returned.


2. Enabling and Configuring Local In-Memory Caching βš™οΈ

Let's start with the simplest form of caching: local in-memory caching. This is great for single-instance applications and for development purposes. It's like having a sticky note on your monitor for things you need to remember quickly.

Getting Started: The Setup

For a Spring Boot application, enabling caching is ridiculously simple.

Step 1: Add the Cache Starter Dependency

In your pom.xml, make sure you have the cache starter dependency:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

Step 2: Enable Caching

Add the @EnableCaching annotation to your main application class or any configuration class.

java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class CachingApplication {

    public static void main(String[] args) {
        SpringApplication.run(CachingApplication.class, args);
    }
}

And... that's it! By default, Spring Boot will configure a ConcurrentHashMap as the cache store. No, seriously, that's all you need to get started. It's almost suspiciously easy.

Configuring the Cache Manager

While the default ConcurrentHashMap works, you might want more control, like setting an expiration policy. For this, you can configure a CacheManager. Let's use Caffeine, a popular high-performance in-memory cache.

Step 1: Add the Caffeine Dependency

xml
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>

Step 2: Configure the Cache Manager in application.properties

You can define your caches and their specifications in your application.properties file.

properties
spring.cache.cache-names=products,users
spring.cache.caffeine.spec=expireAfterWrite=10m,maximumSize=500

This configuration creates two caches named products and users. It also specifies that entries in these caches will expire 10 minutes after they are written and the cache can hold a maximum of 500 entries. It's like telling your brain to forget information after 10 minutes to make space for new, more important thoughts... like what to have for lunch.


3. Caching Annotations in Practice: @Cacheable, @CachePut, and @CacheEvict πŸ“

Now for the fun part! Let's see how to use Spring's powerful caching annotations.

@Cacheable: "Remember This for Me"

The @Cacheable annotation is used on a method to indicate that its result should be cached.

The Problem: You have a method that fetches a product by its ID from the database. This is a frequent and potentially slow operation.

java
@Service
public class ProductService {

    public Product getProductById(String id) {
        // Simulating a slow database call
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Product(id, "Sample Product");
    }
}

Every time you call getProductById("123"), it will take 2 seconds.

The Solution with @Cacheable:

java
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    @Cacheable(value = "products", key = "#id")
    public Product getProductById(String id) {
        // Simulating a slow database call
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Fetching product with ID " + id + " from the database.");
        return new Product(id, "Sample Product");
    }
}
  • value = "products": This specifies the name of the cache to use.
  • key = "#id": This is a Spring Expression Language (SpEL) expression that defines the cache key. Here, we are using the id parameter of the method as the key.

The first time you call getProductById("123"), the method will execute, take 2 seconds, print the log message, and the result will be stored in the "products" cache with the key "123". The next time you call getProductById("123"), the result will be fetched directly from the cache, and the method body will not be executed. It will be lightning fast!

@CachePut: "Update This for Me"

@CachePut is used when you want to update the cache without interfering with the method execution. The method will always be executed, and its result will be placed into the cache.

The Problem: You have a method to update a product's details. You want the updated product to be reflected in the cache.

The Solution with @CachePut:

java
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    @CachePut(value = "products", key = "#product.id")
    public Product updateProduct(Product product) {
        // Logic to update the product in the database
        System.out.println("Updating product with ID " + product.getId() + " in the database.");
        return product;
    }
}

When you call updateProduct(), the method will execute, update the product in the database, and then the returned Product object will update the entry in the "products" cache with the corresponding key.

@CacheEvict: "Forget This for Me"

@CacheEvict is used to remove one or more entries from the cache.

The Problem: When a product is deleted from your system, you also need to remove it from the cache to avoid serving stale data.

The Solution with @CacheEvict:

java
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    @CacheEvict(value = "products", key = "#id")
    public void deleteProduct(String id) {
        // Logic to delete the product from the database
        System.out.println("Deleting product with ID " + id + " from the database.");
    }
}

Calling deleteProduct("123") will execute the method and remove the entry with the key "123" from the "products" cache.

You can also evict all entries from a cache:

java
@CacheEvict(value = "products", allEntries = true)
public void deleteAllProducts() {
    // Logic to delete all products
}

4. Scaling Up: Moving to Distributed Caching with Spring Data Redis 🌐

Local in-memory caching is fantastic, but it has a limitation: it's local to a single application instance. What happens when you deploy multiple instances of your application behind a load balancer for high availability and scalability? Each instance will have its own local cache, leading to data inconsistency. A request to one instance might return fresh data, while a request to another might return stale data from its local cache. This is where distributed caching comes to the rescue.

A distributed cache is an external service that is shared by all instances of your application. Redis is a very popular choice for a distributed cache.

Getting Started with Spring Data Redis

Step 1: Add the Redis Starter Dependency

In your pom.xml, add the following dependency:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Step 2: Configure Redis Connection

In your application.properties, configure the connection to your Redis server:

properties
spring.redis.host=localhost
spring.redis.port=6379

And... that's it! Spring Boot's auto-configuration will detect the Redis dependency and configure a RedisCacheManager. Your @Cacheable, @CachePut, and @CacheEvict annotations will now use Redis as the cache store without you having to change a single line of your service code. The power of abstraction!

A Funny Exaggeration: Imagine trying to coordinate sticky notes across a dozen desks in an office. That's what you'd be doing without a distributed cache. With Redis, it's like having a giant, shared whiteboard that everyone in the office can see and update in real-time.


Further Reading and References πŸ“š

For those who wish to venture deeper into the caching rabbit hole, here are some excellent resources:

Challenge

You are tasked with implementing a caching layer for a ProductService to improve its performance. Your goal is to apply the correct Spring caching annotations to the service methods based on the following requirements:

  1. getProductById(Long id): Cache the returned Product. Subsequent calls with the same id should retrieve the result from the cache. Use the cache named products and use the method's id parameter as the cache key.
  2. updateProduct(Product product): This method must always execute. After execution, it must update the corresponding entry in the products cache with the new product data. The cache key should be derived from the id field of the incoming Product object.
  3. deleteProduct(Long id): When a product is deleted, its entry must be removed from the products cache. Use the method's id parameter to identify the entry to evict.
  4. refreshAllProducts(): This method is used to signal a full data refresh. It must clear the entire products cache when called.

Add the necessary annotations directly above each method signature in the ProductService class. Do not modify the method bodies or the supporting code.

Expected result

The ProductService class should be correctly annotated to manage the products cache according to the requirements.

  • The getProductById method must have the annotation @Cacheable(value = "products", key = "#id").
  • The updateProduct method must have the annotation @CachePut(value = "products", key = "#product.id").
  • The deleteProduct method must have the annotation @CacheEvict(value = "products", key = "#id").
  • The refreshAllProducts method must have the annotation @CacheEvict(value = "products", allEntries = true).
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.