Java – ehcache key type

In ehcache, when adding elements to the cache:

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

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

I see that I can give objects as key indicators

How to use this "complex" key, which consists of multiple ints ((userid, siteid,...), rather than a string as an index)

thank you

Solution

Wrap it in a new class:

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

Then (assuming you have defined the appropriate constructor):

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

For simple cases, you can use string concatenation:

cache.put(new Element(userId + ":" + siteId,value));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>