ehcache is a hugely configurable beast, and the examples are fairly complex, often involving many layers of interfaces.
Has anyone come across the simplest example which just caches something like a single number in memory (not distributed, no XML, just as few lines of java as possible). The number is then cached for say 60 seconds, then the next read request causes it to get a new value (e.g. by calling Random.nextInt() or similar)
Is it quicker/easier to write our own cache for something like this with a singleton and a bit of synchronization?
No Spring please.
Best Answer
EhCache comes with a failsafe configuration that has some reasonable expiration time (120 seconds). This is sufficient to get it up and running.
Imports:
Then, creating a cache is pretty simple:
This creates a cache called
test
. You can have many different, separate caches all managed by the sameCacheManager
. Adding(key, value)
pairs to this cache is as simple as:Retrieving a value for a given key is as simple as:
If you attempt to access an element after the default 120 second expiration period, the cache will return null (hence the check to see if
elt
is null). You can adjust the expiration period by creating your ownehcache.xml
file - the documentation for that is decent on the ehcache site.