Spring缓存用实例变量和参数作为键
-
21-12-2019 - |
题
我正在使用ehcache来缓存方法结果。关键必须是成员对象和方法参数的组合。我的班级看起来像:
Class A {
private B b;
@Cacheable(value="someCache",key="some key based on B and C")
public Result getResult(C c){
......
}
.
我需要基于B和C的关键。 我参考了 https://code.google.com/p/ ehcache-spring注释/问题/细节?id= 69 ,但它们没有指定如何在密钥生成中包含方法参数。有人可以帮助我吗?
解决方案 2
我已经实现了一个自定义密钥生成器来解决这个问题。仍然我认为这可以通过ehcache解决而不使用自定义密钥生成器。但我无法在任何地方得到答案。请看我以下的答案:
@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;
}
}
}
. 其他提示
您可以使用密钥中的A
访问root.target
对象。例如。
key="#root.target.b.id+'-'+#c.id"
. 不隶属于 StackOverflow