EhCache密钥类型

Mat*_*oli 10 java ehcache

在EhCache中,向缓存添加元素时:

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

// Element constructors :
Element(Object key, Object value)
Run Code Online (Sandbox Code Playgroud)

我看到我可以给出一个Object关键指数.

我如何使用它来拥有一个"复杂"键,由多个int组成:(userId,siteId,...)而不是字符串作为索引?

谢谢

Boz*_*zho 14

将它包装在一个新类中:

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

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

cache.put(new Element(new CacheKey(userId, siteId), value);
Run Code Online (Sandbox Code Playgroud)

对于简单的情况,您可以使用字符串连接:

cache.put(new Element(userId + ":" + siteId, value));
Run Code Online (Sandbox Code Playgroud)

  • 尺寸不会成为问题,不用担心.ehcache将获取对象的哈希值(因此您应该覆盖包含所有字段的哈希码) (2认同)