问题
I am using ehcache for caching the method results. The key has to be a combination of both member object and method's parameter. My class looks something like:
Class A {
private B b;
@Cacheable(value="someCache",key="some key based on B and C")
public Result getResult(C c){
......
}
I need the key to be based on B and C. I referred https://code.google.com/p/ehcache-spring-annotations/issues/detail?id=69 but they did not specify how to include the method parameter in the key generation. Could someone help me with this?
回答1:
you can access the A
object with root.target
in the key. e.g.
key="#root.target.b.id+'-'+#c.id"
回答2:
I have implemented a custom key generator to solve this. Still I think this can be solved by ehcache without using a custom key generator. But i could not get the answer anywhere. Please see my answer below:
@Component
public class Home {
private Parameter param;
@Cacheable(cacheName = "homeCache",
keyGenerator = @KeyGenerator(name = "com.myapp.cache.Home.ParamKeyGenerator"))
public Result getPerson(Person p) {
//Do something with p
return result;
}
public Parameter getParam() {
return param;
}
public void setParam(Parameter param) {
this.param = param;
}
public static class ParamKeyGenerator implements CacheKeyGenerator<Serializable> {
public Serializable generateKey(MethodInvocation methodInvocation) {
Object[] obj = methodInvocation.getArguments();
Home h = (Home) methodInvocation.getThis();
return this.generateKey(obj[0], h.getParam());
}
public Serializable generateKey(Object... data) {
String key = ((Person) data[0]).getName() + ((Parameter) data[1]).getName();
System.out.println("generating key: " + key);
return key;
}
}
}
来源:https://stackoverflow.com/questions/22019291/spring-cache-with-instance-variable-and-parameter-as-key