Custom Key Generator Spring Cache

Custom Key Generator Spring Cache Average ratng: 9,1/10 2447 reviews

I encountered a problem with Spring Frameworks default Cache KeyGenerator. It seems to often encounter conflicts and it appears to have been recorded on this issue. I know this question has already been marked as answered, but I thought I would share how I resolved this. The cache is nothing but a key-value store which stores the data based on certain key. In Spring framework based caching, the method arguments of cached method acts as the source of Key generation. Every key is essentially the Hash-code of these arguments.

In the last example we saw how to use a custom KeyGenerator by using CacheConfig#keyGenerator. In this example, we will see how to register our custom KeyGenerator globally by implementing CachingConfigurer interface or by extending its adapter class CachingConfigurerSupport.

Example

Spring Cache Custom Key Generator

Custom Key Generator Spring Cache Download

Java Config

  1. Response Generator - Specify the name of a Response Generator that directs the cache strategy to use a custom-built Spring bean to generate a response that combines data from both the new request and the cached response. Click the green plus sign next to the field to create a new Spring bean for your caching strategy to reference.
  2. By default a cache key is generated by a key generator that uses Arrays.deepHashCode(Object) and Arrays.deepEquals(Object, Object) on the method parameters. The cache lookup based on this key is similar to a HashMap lookup.

CachingConfigurer interface is to be implemented by @Configuration classes annotated with @EnableCaching. It provides various methods to configure or customize caching abstraction.

We are also overriding cacheManager() method to register our cache provider. /regcure-pro-3215-license-key-generator.html. Etekcity wireless adapter driver.

The Custom KeyGenerator

Spring cache custom key generator example

A service bean

As compare to the last example, we don't need to use @CacheConfig#keyGenerator or @Cacheable#keyGenerator anymore.

The main class

Example Project

Dependencies and Technologies Used:

  • spring-context 5.0.4.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.3.9