Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EhCache key type

Tags:

java

ehcache

In EhCache, when adding an element to the cache :

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

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

I see I can give an Object as the key index.

How can I use this to have a "complex" key, composed of multiple int : (userId,siteId,...) instead of a string as an index ?

Thanks

like image 476
Matthieu Napoli Avatar asked May 06 '11 08:05

Matthieu Napoli


People also ask

What is ehcache used for?

Ehcache is a standards-based caching API that is used by Integration Server. Caching enables an application to fetch frequently used data from memory (or other nearby resource) rather than having to retrieve it from a database or other back-end system each time the data is needed.

What is ehcache XML?

Introduction. Caches can be configured in Ehcache either declaratively in XML, or by creating caches programmatically and specifying their parameters in the constructor. While both approaches are fully supported, it is generally a good idea to separate the cache configuration from runtime use.


1 Answers

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)
}

And 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));
like image 78
Bozho Avatar answered Sep 28 '22 03:09

Bozho