Learnitweb

Advanced Redis Caching in Spring Boot: Cache Eviction and Scheduled Cache Clearing

In previous lectures, we implemented Redis caching for a Fibonacci service using the @Cacheable annotation. While caching improves performance, it introduces the need for cache management strategies, including eviction and scheduled clearing.

This tutorial explains these concepts in detail.


1. Why Cache Eviction is Important

When you use @Cacheable:

  • Cached data persists indefinitely unless explicitly removed.
  • In real-world applications, data can change (e.g., database updates). Serving stale data from the cache can lead to inconsistent or incorrect responses.

Scenarios where eviction is necessary:

  • Update or delete operations (PUT, POST, DELETE) invalidate the cached data.
  • Data should expire after a certain time (e.g., temporary metrics, time-bound calculations).

2. Using @CacheEvict to Clear Cache

The @CacheEvict annotation allows you to remove cache entries programmatically.

Example:

package com.example.fib.service;

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

@Service
public class FibonacciService {

    @CacheEvict(value = "fibonacci", key = "#index")
    public void clearFibonacciCache(int index) {
        // This method will clear the cache for the specific index
    }
}

Key Points:

  • value = "fibonacci" specifies the cache bucket in Redis.
  • key = "#index" clears only the cache entry for that Fibonacci index.
  • Typically, GET requests use @Cacheable, while POST/PUT/DELETE requests use @CacheEvict.

3. Practical Example

  1. Compute Fibonacci number 45 using @Cacheable:
GET /fib/45
  • First request: Takes time (calculation occurs).
  • Subsequent requests: Fast (retrieved from Redis cache).
  1. Clear cache for index 45:
POST /fib/clear/45
  • Next request for index 45 recalculates the value.
  • Cache is updated after calculation, subsequent requests are fast again.

Note: Without eviction, cached values would remain indefinitely, potentially serving stale data.


4. Evicting Cache for Objects

When caching objects, you can specify a key based on a field of the object:

@CacheEvict(value = "product", key = "#product.id")
public void updateProduct(Product product) {
    // Update product in DB
    // Cache entry for product.id will be removed
}
  • Ensures that subsequent GET requests fetch fresh data from the database.
  • Avoids serving outdated product information.

5. Scheduled Cache Clearing

Sometimes, you want to clear cache automatically at regular intervals, independent of API calls.

Step 1: Enable Scheduling

Add @EnableScheduling to your Spring Boot main class:

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

Step 2: Create a Scheduled Cache Eviction Method

package com.example.fib.service;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledCacheEvictService {

    @CacheEvict(value = "fibonacci", allEntries = true)
    @Scheduled(fixedRate = 10000) // every 10 seconds
    public void clearAllFibonacciCache() {
        System.out.println("Cleared all Fibonacci cache entries.");
    }
}

Explanation:

  • allEntries = true clears all keys in the fibonacci cache.
  • @Scheduled(fixedRate = 10000) runs this method every 10 seconds.
  • Useful for temporary data or metrics that should be refreshed periodically.

6. How It Works

  1. A Fibonacci calculation is performed and cached using @Cacheable.
  2. Subsequent requests retrieve the cached value.
  3. When clearFibonacciCache(index) or scheduled eviction runs, cache entries are removed.
  4. Future requests will trigger recalculation, after which results are cached again.

Behavior Example:

RequestIndexAction
GET44Calculate & cache
GET44Retrieve from cache
POST44Evict cache for 44
GET44Recalculate & cache
Scheduled EvictionAllClear all cached entries every 10 sec

7. Summary

  • @Cacheable: Stores method results in cache.
  • @CacheEvict: Clears specific cache entries or all entries (allEntries = true).
  • Scheduled eviction allows automatic clearing at regular intervals.
  • Cache eviction is essential to avoid stale data, especially for mutable objects.