2011-05-06 69 views
10

在ehcache的,加入到高速缓存元素时:ehcache的密钥类型

cache.put(new Element("key1", "value1")); 

// Element constructors : 
Element(Object key, Object value) 

我看我可以给一个Object作为密钥索引。

我怎样才能使用这个有一个“复杂”的键,由多个int:(userId,siteId,...)而不是一个字符串作为索引?

感谢

+0

这是一个很好的问题。如何为缓存或地图制作多维关键字? @Bozho下面的答案或多或少是正确的,除了字符串concat。创建新对象所花费的时间会更少,并且它很可能会更小,因为您没有(粗略估计)该连接隐含的近5个字符串创建(userId to string,inline“:”,userId +的连接“: “,siteId为string,prev str + siteId str的新字符串concat)。 – 2011-05-06 10:19:00

回答

14

新一类把它包:

public class CacheKey implements Serializable { 
    private int userId; 
    private int siteId; 
    //override hashCode() and equals(..) using all the fields (use your IDE) 
} 

然后(假设您已经定义适当的构造函数):

cache.put(new Element(new CacheKey(userId, siteId), value); 

对于简单的情况下,你可以使用字符串级联:

cache.put(new Element(userId + ":" + siteId, value)); 
+0

字符串连接对我来说并不是最好的,因为我需要尽可能小的内存大小(许多记录)。使用'Serializable',我能够拥有最轻/最短的密钥吗? EhCache将如何使用Key对象?谢谢 – 2011-05-06 09:24:20

+2

的大小不会是一个问题,不要担心。 ehcache将得到对象的散列(因此你应该覆盖包含所有字段的散列码) – Bozho 2011-05-06 09:27:14

+0

对不起,但有必要实现'Serializable'? '可比较'是否足够? – OldCurmudgeon 2012-11-06 17:10:21

相关问题