Java – ehcache automatically generates keys and @ cacheable spring annotations
Does anyone know how ehcache's default key generation works? If I have the following methods:
@Cacheable(cacheName = CACHE_KEY) // CACHE_KEY is static final field.
public List<DataObject> list(
int firstRecord,int maxRecords,int pageSize,FilterObject filter) {
....
}
Filterobject is a custom POJO. What should I expect to be the actual cache key?
What I have observed is that when different filterobject instances are used without changing other parameters of my method call, it always produces the same result - the result of the first call is cached and returned
It may be the filterobject POJO that causes this behavior - I think it's some serialization or ToString () is a problem because I didn't override the relevant methods
I still can't find the exact information about how to form the cache key of this method in ehcache's website and @ cacheable annotation document I am very grateful for any information and suggestions on this topic
Solution
This is the default key generator
public class DefaultKeyGenerator implements KeyGenerator {
public static final int NO_PARAM_KEY = 0;
public static final int NULL_PARAM_KEY = 53;
public Object generate(Object target,Method method,Object... params) {
if (params.length == 1) {
return (params[0] == null ? NULL_PARAM_KEY : params[0]);
}
if (params.length == 0) {
return NO_PARAM_KEY;
}
int hashCode = 17;
for (Object object : params) {
hashCode = 31 * hashCode + (object == null ? NULL_PARAM_KEY : object.hashCode());
}
return Integer.valueOf(hashCode);
}
}
As you can see, it combines the hash codes of each method parameter
