Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Caching Implementation with Spring Cache in Microservices

Tech May 19 2

1. Configuration Setup

Import the required dependency in your pom.xml:

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

Configure cache settings in application.yml:

spring:
    cache:
        type: redis
        cache-names: productCache

Add the @EnableCaching annotation to your main application class to activate caching functionality.

2. Core Cache Annotations

2.1 @Cacheable

Place @Cacheable above service layer implementation methods:

@Cacheable(value = {"inventoryCache", "stockCache"}, key = "'productId:' + #id")
public Product getProductById(Long id) {
    return productRepository.findById(id);
}

This annotation stores method results in cache. When subsequent calls occur with the same parameters, the cached result is returned immediately without executing the method body. If no cached entry exists, the method executes normally and the result gets stored for future requests.

The value parameter defines cache namespace(s). When key is omitted, the cache name serves as the key prefix.

2.2 @CacheEvict

Understanding cache synchronization strategies is essential before implementing eviction:

Invalidation Pattern: Write data to the database, then remove the corresponding cache entry. When the next request arrives, the cache rebuilds dynamically.

Write-Through Pattern: Write data to the database, then immediately write the modified value to cache.

Apply @CacheEvict to methods that modify cached data:

@CacheEvict(value = "inventoryCache", key = "'productId:' + #product.id")
public void updateProduct(Product product) {
    productRepository.save(product);
}

When this method executes, the specified cache entry is automatically removed, implementing the invalidasion pattern.

For removing all antries within a cache namespace, use allEntries = true:

@CacheEvict(value = "inventoryCache", allEntries = true)
public void clearInventoryCache() {
    // operations that require full cache invalidation
}

Note: Unlike @Cacheable, @CacheEvict does not support multiple cache names in the value parameter.

The @CachePut annotation corresponds to the write-through pattern, updating cache entries after database modifications without affecting method return values.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.