Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hello world example for ehcache?

Tags:

ehcache

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.

like image 666
wingnut Avatar asked Jun 02 '11 11:06

wingnut


People also ask

What is Ehcache and how it should be implemented?

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.

How do you use Ehcache in spring?

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 .

What is Ehcache xml?

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.


1 Answers

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.

like image 174
jbrookover Avatar answered Sep 24 '22 08:09

jbrookover