Skip to main content

Chapter 2: Caching with Spring Cache and Redis

Chapter Objectives​

  • Understand caching concepts
  • Configure Spring Cache with Redis
  • Use @Cacheable, @CacheEvict, @CachePut annotations
  • Implement effective caching strategies
  • Manage expiration and invalidation

1. Introduction to Caching​

1.1 Why Cache​

Without cache:
Client → API → Service → Database → Service → API → Client
↓ ↓
10ms 100ms = 110ms total

With cache:
Client → API → Cache → API → Client
↓ ↓
10ms 1ms = 11ms total (10x faster)

1.2 Types of Cache​

TypeDescriptionExample
LocalApplication memoryConcurrentHashMap, Caffeine
DistributedShared external serverRedis, Memcached
CDNStatic contentCloudFlare, AWS CloudFront

1.3 Caching Strategies​

StrategyDescriptionUsage
Cache-AsideApp manages cacheGeneral
Read-ThroughCache manages readsFrequent reads
Write-ThroughWrites to cache and DBStrong consistency
Write-BehindWrites cache, DB asyncPerformance

2. Spring Cache Configuration with Redis​

2.1 Maven Dependencies​

<dependencies>
<!-- Spring Cache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

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

<!-- Connection pool -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
</dependencies>

2.2 application.yml Configuration​

spring:
data:
redis:
host: localhost
port: 6379
password: ""
timeout: 2000ms
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 2
max-wait: -1ms

cache:
type: redis
redis:
time-to-live: 3600000 # 1 hour in ms
cache-null-values: false
use-key-prefix: true
key-prefix: "myapp:"

2.3 Java Configuration​

package com.example.cache.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableCaching
public class CacheConfig {

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
// Default configuration
RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1))
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new StringRedisSerializer()))
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()))
.disableCachingNullValues();

// Specific cache configurations
Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();

// Products cache: TTL 30 minutes
cacheConfigs.put("products", defaultConfig.entryTtl(Duration.ofMinutes(30)));

// Users cache: TTL 1 hour
cacheConfigs.put("users", defaultConfig.entryTtl(Duration.ofHours(1)));

// Search cache: TTL 5 minutes
cacheConfigs.put("search", defaultConfig.entryTtl(Duration.ofMinutes(5)));

return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(defaultConfig)
.withInitialCacheConfigurations(cacheConfigs)
.transactionAware()
.build();
}
}

3. Cache Annotations​

3.1 @Cacheable​

Caches the result of a method.

@Service
public class ProductService {

private final ProductRepository productRepository;

public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}

// Simple cache with ID as key
@Cacheable(value = "products", key = "#id")
public Product getProductById(Long id) {
log.info("Fetching product {} from database", id);
return productRepository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));
}

// Cache with composite key
@Cacheable(value = "products", key = "#category + '_' + #page")
public List<Product> getProductsByCategory(String category, int page) {
log.info("Fetching products for category {} page {}", category, page);
return productRepository.findByCategory(category, PageRequest.of(page, 20));
}

// Conditional cache
@Cacheable(value = "products", key = "#id", condition = "#id > 0")
public Product getProductConditional(Long id) {
return productRepository.findById(id).orElse(null);
}

// Do not cache if null
@Cacheable(value = "products", key = "#id", unless = "#result == null")
public Product getProductUnlessNull(Long id) {
return productRepository.findById(id).orElse(null);
}
}

3.2 @CacheEvict​

Removes entries from the cache.

@Service
public class ProductService {

// Remove a specific entry
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}

// Remove all entries from the cache
@CacheEvict(value = "products", allEntries = true)
public void clearProductCache() {
log.info("Product cache cleared");
}

// Remove before execution
@CacheEvict(value = "products", key = "#id", beforeInvocation = true)
public void deleteProductBeforeInvocation(Long id) {
productRepository.deleteById(id);
}

// Remove after update
@CacheEvict(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
return productRepository.save(product);
}
}

3.3 @CachePut​

Updates the cache without checking if it exists.

@Service
public class ProductService {

// Update the cache with the new product
@CachePut(value = "products", key = "#product.id")
public Product createProduct(Product product) {
return productRepository.save(product);
}

// Update the cache after modification
@CachePut(value = "products", key = "#result.id")
public Product updateProduct(Long id, ProductRequest request) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));
product.setName(request.getName());
product.setPrice(request.getPrice());
return productRepository.save(product);
}
}

3.4 @Caching (Combination)​

@Service
public class ProductService {

@Caching(
put = { @CachePut(value = "products", key = "#result.id") },
evict = {
@CacheEvict(value = "productList", allEntries = true),
@CacheEvict(value = "search", allEntries = true)
}
)
public Product saveProduct(Product product) {
return productRepository.save(product);
}
}

3.5 @CacheConfig (Class Configuration)​

@Service
@CacheConfig(cacheNames = "products")
public class ProductService {

@Cacheable(key = "#id") // Uses "products" cache
public Product getById(Long id) { ... }

@CacheEvict(key = "#id") // Uses "products" cache
public void delete(Long id) { ... }
}

4. Custom Cache Keys​

4.1 SpEL for Keys​

// Simple parameter
@Cacheable(key = "#id")

// Object property
@Cacheable(key = "#product.id")

// Concatenation
@Cacheable(key = "#category + ':' + #page")

// Method on parameter
@Cacheable(key = "#name.toLowerCase()")

// Result (for @CachePut)
@CachePut(key = "#result.id")

// Root variables
@Cacheable(key = "#root.method.name + '_' + #id")
@Cacheable(key = "#root.targetClass.simpleName + '_' + #id")

4.2 Custom KeyGenerator​

@Configuration
public class CacheConfig {

@Bean
public KeyGenerator customKeyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getSimpleName());
sb.append(".");
sb.append(method.getName());
for (Object param : params) {
sb.append("_");
sb.append(param != null ? param.toString() : "null");
}
return sb.toString();
};
}
}
@Cacheable(value = "products", keyGenerator = "customKeyGenerator")
public List<Product> searchProducts(String name, String category, Double maxPrice) {
// Generated key: ProductService.searchProducts_laptop_electronics_1000.0
return productRepository.search(name, category, maxPrice);
}

5. RedisTemplate for Advanced Operations​

5.1 Configuration​

@Configuration
public class RedisConfig {

@Bean
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);

// Serialize keys as String
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());

// Serialize values as JSON
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

template.afterPropertiesSet();
return template;
}
}

5.2 Operations​

@Service
public class RedisCacheService {

private final RedisTemplate<String, Object> redisTemplate;

public RedisCacheService(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}

// String operations
public void setValue(String key, Object value, Duration ttl) {
redisTemplate.opsForValue().set(key, value, ttl);
}

public Object getValue(String key) {
return redisTemplate.opsForValue().get(key);
}

public Boolean setIfAbsent(String key, Object value, Duration ttl) {
return redisTemplate.opsForValue().setIfAbsent(key, value, ttl);
}

// Hash operations
public void setHashField(String key, String field, Object value) {
redisTemplate.opsForHash().put(key, field, value);
}

public Object getHashField(String key, String field) {
return redisTemplate.opsForHash().get(key, field);
}

public Map<Object, Object> getHash(String key) {
return redisTemplate.opsForHash().entries(key);
}

// List operations
public void addToList(String key, Object value) {
redisTemplate.opsForList().rightPush(key, value);
}

public List<Object> getList(String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}

// Set operations
public void addToSet(String key, Object... values) {
redisTemplate.opsForSet().add(key, values);
}

public Set<Object> getSet(String key) {
return redisTemplate.opsForSet().members(key);
}

// TTL and deletion
public Boolean expire(String key, Duration ttl) {
return redisTemplate.expire(key, ttl);
}

public Boolean delete(String key) {
return redisTemplate.delete(key);
}

public Long deleteByPattern(String pattern) {
Set<String> keys = redisTemplate.keys(pattern);
if (keys != null && !keys.isEmpty()) {
return redisTemplate.delete(keys);
}
return 0L;
}

public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
}

6. Cache Patterns​

6.1 Cache-Aside (Lazy Loading)​

@Service
public class ProductCacheService {

private final ProductRepository repository;
private final RedisTemplate<String, Product> redisTemplate;
private static final Duration CACHE_TTL = Duration.ofMinutes(30);

public Product getProduct(Long id) {
String key = "product:" + id;

// 1. Check the cache
Product cached = redisTemplate.opsForValue().get(key);
if (cached != null) {
return cached;
}

// 2. Cache miss: load from DB
Product product = repository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));

// 3. Cache it
redisTemplate.opsForValue().set(key, product, CACHE_TTL);

return product;
}

public void updateProduct(Product product) {
// 1. Update DB
repository.save(product);

// 2. Invalidate cache
String key = "product:" + product.getId();
redisTemplate.delete(key);
}
}

6.2 Write-Through​

@Service
public class ProductWriteThroughService {

public Product saveProduct(Product product) {
// 1. Save to DB
Product saved = repository.save(product);

// 2. Update cache immediately
String key = "product:" + saved.getId();
redisTemplate.opsForValue().set(key, saved, CACHE_TTL);

return saved;
}
}

6.3 Cache Warming​

@Component
public class CacheWarmer implements ApplicationRunner {

private final ProductRepository productRepository;
private final RedisTemplate<String, Product> redisTemplate;

@Override
public void run(ApplicationArguments args) {
log.info("Warming up product cache...");

// Load popular products at startup
List<Product> popularProducts = productRepository.findTop100ByOrderBySalesDesc();

popularProducts.forEach(product -> {
String key = "product:" + product.getId();
redisTemplate.opsForValue().set(key, product, Duration.ofHours(24));
});

log.info("Cache warmed with {} products", popularProducts.size());
}
}

7. Error Handling​

7.1 CacheErrorHandler​

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

@Override
public CacheErrorHandler errorHandler() {
return new SimpleCacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException ex, Cache cache, Object key) {
log.warn("Cache get error for key {} in cache {}: {}",
key, cache.getName(), ex.getMessage());
// Do not propagate error - continue without cache
}

@Override
public void handleCachePutError(RuntimeException ex, Cache cache,
Object key, Object value) {
log.warn("Cache put error for key {} in cache {}: {}",
key, cache.getName(), ex.getMessage());
}

@Override
public void handleCacheEvictError(RuntimeException ex, Cache cache, Object key) {
log.warn("Cache evict error for key {} in cache {}: {}",
key, cache.getName(), ex.getMessage());
}

@Override
public void handleCacheClearError(RuntimeException ex, Cache cache) {
log.warn("Cache clear error for cache {}: {}",
cache.getName(), ex.getMessage());
}
};
}
}

8. Monitoring​

8.1 Actuator Endpoints​

management:
endpoints:
web:
exposure:
include: health,caches,metrics
endpoint:
caches:
enabled: true
# List caches
curl http://localhost:8080/actuator/caches

# Cache metrics
curl http://localhost:8080/actuator/metrics/cache.gets
curl http://localhost:8080/actuator/metrics/cache.puts
curl http://localhost:8080/actuator/metrics/cache.evictions

8.2 Custom Metrics​

@Service
public class ProductService {

private final MeterRegistry meterRegistry;
private final Counter cacheHits;
private final Counter cacheMisses;

public ProductService(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.cacheHits = meterRegistry.counter("product.cache.hits");
this.cacheMisses = meterRegistry.counter("product.cache.misses");
}

public Product getProduct(Long id) {
Product cached = getFromCache(id);
if (cached != null) {
cacheHits.increment();
return cached;
}

cacheMisses.increment();
return loadFromDatabase(id);
}
}

9. Summary​

Annotations​

AnnotationAction
@CacheableReads from cache or executes and caches
@CachePutAlways executes and updates cache
@CacheEvictRemoves from cache
@CachingCombines multiple annotations
@CacheConfigClass-level configuration

Best Practices​

  1. Define appropriate TTLs per data type
  2. Use meaningful and consistent keys
  3. Invalidate cache on updates
  4. Handle Redis errors gracefully
  5. Monitor hit/miss ratios
  6. Do not cache sensitive data
  7. Plan cache warming for critical data

Next Chapter: Messaging with RabbitMQ

Back to Module 14