2014-02-25 18 views
0

我正在使用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-annotations/issues/detail?id=69,但他們沒有說明如何將在密鑰生成方法的參數。有人可以幫助我嗎?

回答

0

我已經實現了一個自定義密鑰生成器來解決這個問題。不過我認爲這可以通過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; 
     } 
    } 
} 
1

您可以在密鑰中使用root.target訪問A對象。例如

key="#root.target.b.id+'-'+#c.id" 
+0

道歉。我想我給了Spring緩存註釋。在ehcache的@Cacheable註解中,我們沒有'key'。 @Cacheable(cacheName =「homeCache」,keyGenerator = .......) – falcon