0 day streak
java / expert
Snippet

Fine-grained Cache Keys with Custom KeyGenerator

Default Spring Caching uses a SimpleKeyGenerator which might lead to collisions in complex environments. Implementing a custom KeyGenerator provides full control over how keys are hashed, enabling developers to include class metadata or specific parameter attributes to ensure cache isolation and efficiency.

snippet.java
java
1
2
3
4
5
6
7
8
9
@Component("myKeyGenerator")
public class CustomCacheKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object target, Method method, Object... params) {
return target.getClass().getSimpleName() + "_"
+ method.getName() + "_"
+ Arrays.deepHashCode(params);
}
}
spring
Breakdown
1
public Object generate(Object target, Method method, Object... params)
Custom logic to derive a unique identifier for a specific method execution.
2
Arrays.deepHashCode(params)
Generates a stable hash code based on the deep contents of the method arguments.