In Spring Cache, you can define the cache key at global level by using the key prefix configuration in conjunction with using the default or implementing a custom key generator. Apart from that, cache key definition at the class and method level is also supported

Let's walk though this tutorial to explore them in more details

Define the cache key at global level

Cache key prefix

You can use the Spring Cache property spring.cache.redis.key-prefix to add the prefix to all generated cache key in Spring Boot applications

spring.cache.redis.key-prefix=hellokoding::

The default key generator

By default, SimpleKeyGenerator in the org.springframework.cache.interceptor package, an implementation of KeyGenerator interface, is used to generate the cache key

SimpleKeyGenerator evaluates parameters of the cache annotated methods (by @Cachable, @CachePut and @CacheEvict). If only one non-null param is existing, it returns the param itself, otherwise the below SimpleKey's toString() method is used for computing all params

@Override
public String toString() {  
    return getClass().getSimpleName() + " [" + StringUtils.arrayToCommaDelimitedString(this.params) + "]";
}

Custom key generator

  • Implement KeyGenerator interface to provide the custom key generator. The following give you an example

  • Register the custom definition to an implementation of CachingConfigurer. The below give you an example with CachingConfigurerSupport
import org.springframework.cache.annotation.CachingConfigurerSupport;  
import org.springframework.cache.interceptor.CacheErrorHandler;  
import org.springframework.context.annotation.Configuration;

@Configuration
public class CachingConfiguration extends CachingConfigurerSupport {  
    @Override
    public KeyGenerator keyGenerator() {
        return new CustomKeyGenerator();
    }
}

Define the cache key at the class and method level

You can define the cache key at class and method level with the key and keyGenerator attributes of the @Cachable, @CachePut and @CacheEvict annotations

  • If key and keyGenerator are empty (by default), Spring Cache will use the SimpleKeyGenerator if no custom key generator implementations have found
@Cacheable(key = "", keyGenerator = "")
public Optional<Product> findById(Long id) {  
    return productRepository.findById(id);
}

With the CustomKeyGenerator implementation, the generated key should be "hellokoding::ProductService_findAll_"

  • Spring Cache uses the Spring Expression Language (SpEL) for computing the cache key
@CachePut(key = "T(java.lang.String).format('%s-%s-%s', #root.target.Class.simpleName, #root.methodName, #product.name)")
public Product save(Product product) {  
    return productRepository.save(product);
}

The generated cache key should be "hellokoding::ProductService-save-Hello Koding" if the product name is "Hello Koding"

Conclusion

In this tutorial, we learned some ways to define the cache key in Spring Cache applications. You can find the full source code at https://github.com/hellokoding/hellokoding-courses/tree/master/springboot-examples/springboot-caching-redis