I'm using Spring caching (with EHCache) on server side defining the cache key(s) within @Cacheable. The problem is that different clients send the same strings that are used as keys with different spelling as they send it case sensitive. The result is that my caches contain more objects than they would have to.
Example: Let's say I have the following caching defined for a certain method:
@Cacheable(value = "myCache", key="{#myString}")
public SomeBusinessObject getFoo(String myString, int foo){
...
}
Now client A sends "abc" (all lowercase) to the Controller. Controller calls getFoo and "abc" is used as key to put an object into the cache. Client B sends "abC" (uppercase C) and instead of returning the cached object for key "abc" a new cache object for key "abC" is created.
How can I avoid the keys to be case sensitive?
I know I could define the cache key to be lowercase like this:
@Cacheable(value = "myCache", key="{#myString.toLowerCase()}")
public SomeBusinessObject getFoo(String myString, int foo){
...
}
This is of course working. But I'm looking for a more general solution. I have many caches and many cache keys and do some @CacheEvict(s) and @CachePut(s) and if I would use that "toLowerCase" approach I would always have to make sure not to forget it anywhere.
As @gaston mentioned, the solution is replacing the default
KeyGenerator
. Implementingorg.springframework.cache.annotation.CachingConfigurer
or extendingorg.springframework.cache.annotation.CachingConfigurerSupport
in yourConfiguration
.Here is a implementation modified from
org.springframework.cache.interceptor.SimpleKeyGenerator
.The original implementation produce key using
SimpleKey
class when@Cacheable
method has more than one argument. Here is another implementation for producing case insensitive key.