以实例变量和参数为键的Spring缓存 [英] Spring cache with instance variable and parameter as key
问题描述
我正在使用ehcache缓存方法结果。键必须是成员对象和方法参数的组合。我的班级看起来像这样:
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){
......
}
我需要基于B和C的密钥。 b我提到了 https://code.google.com/ p / ehcache-spring-annotations / issues / detail?id = 69 ,但他们未指定如何在密钥生成中包括方法参数。有人可以帮我吗?
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?
推荐答案
我已经实现了自定义密钥生成器来解决这个问题。我仍然认为ehcache可以解决此问题,而无需使用自定义密钥生成器。但是我在任何地方都找不到答案。请在下面查看我的答案:
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;
}
}
}
这篇关于以实例变量和参数为键的Spring缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!