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.
EhCache is a widely used, pure Java cache that can be easily integrated with most popular Java frameworks, such as Spring and Hibernate. It is often considered to be the most convenient choice for Java applications since it can be integrated into projects easily.
Spring Caching Example + EhCache To learn how to configure Ehcache, read this official ehcache. xml example. 4.2 Add @Cacheable on the method you want to cache. 4.3 Enable Caching with @EnableCaching and declared a EhCacheCacheManager .
XML Configuration. BigMemory Max uses Ehcache as its user-facing interface and is configured using the Ehcache configuration system. By default, Ehcache looks for an ASCII or UTF8 encoded XML configuration file called ehcache. xml at the top level of the Java classpath.
EhCache comes with a failsafe configuration that has some reasonable expiration time (120 seconds). This is sufficient to get it up and running.
Imports:
import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element;
Then, creating a cache is pretty simple:
CacheManager.getInstance().addCache("test");
This creates a cache called test
. You can have many different, separate caches all managed by the same CacheManager
. Adding (key, value)
pairs to this cache is as simple as:
CacheManager.getInstance().getCache("test").put(new Element(key, value));
Retrieving a value for a given key is as simple as:
Element elt = CacheManager.getInstance().getCache("test").get(key); return (elt == null ? null : elt.getObjectValue());
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 own ehcache.xml
file - the documentation for that is decent on the ehcache site.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With