In this tutorial, we will show you two examples to help you getting started with Ehcache.
Tools used :
- Ehcache 2.9
- Maven 3
- Gradle 2
- JDK 1.7
P.S Ehcache required JDK 1.5 or above.
1. Project Directory Structure
2. Hello World
Assume this is a Maven project :
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.9.0</version>
</dependency>
Read comments for self-explanatory.
package com.mkyong.cache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class HelloEhCache{
public static void main(String[] args) {
//1. Create a cache manager
CacheManager cm = CacheManager.getInstance();
//2. Create a cache called "cache1"
cm.addCache("cache1");
//3. Get a cache called "cache1"
Cache cache = cm.getCache("cache1");
//4. Put few elements in cache
cache.put(new Element("1","Jan"));
cache.put(new Element("2","Feb"));
cache.put(new Element("3","Mar"));
//5. Get element from cache
Element ele = cache.get("1");
//6. Print out the element
String output = (ele == null ? null : ele.getObjectValue().toString());
System.out.println(output);
//7. Is key in cache?
System.out.println(cache.isKeyInCache("1"));
System.out.println(cache.isKeyInCache("5"));
//8. shut down the cache manager
cm.shutdown();
}
}
Output
06:03:37.007 [main] WARN n.s.e.config.ConfigurationFactory - No configuration found.
Configuring ehcache from ehcache-failsafe.xml found in the classpath:
//...
Jan
true
false
//...
More APIs info, refer to this Performing Basic Cache Operations
The Ehcache framework can be configured via
ehcache.xml file, if this file is not available, a default ehcache-failsafe.xml will be used.
2. Ehcache Configuration
In this example, we will show you how to configure Ehcache via an ehcache.xml file.
Assume this is a Gradle project :
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
version = '1.0'
// Uses JDK 7
sourceCompatibility = 1.7
targetCompatibility = 1.7
// Get dependencies from Maven central repository
repositories {
mavenCentral()
}
//Project dependencies
dependencies {
compile 'net.sf.ehcache:ehcache:2.9.0'
}
Create an ehcache.xml, and put it into the src/main/resources folder.
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<!-- By default, Ehcache stored the cached files in temp folder. -->
<!-- <diskStore path="java.io.tmpdir" /> -->
<!-- Ask Ehcache to store cache in this path -->
<diskStore path="c:\\cache" />
<!-- Sample cache named cache1
This cache contains a maximum in memory of 10000 elements, and will expire
an element if it is idle for more than 5 minutes and lives for more than
10 minutes.
If there are more than 10000 elements it will overflow to the
disk cache, which in this configuration will go to wherever java.io.tmp is
defined on your system. On a standard Linux system this will be /tmp" -->
<cache name="cache1"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="1000"
eternal="false"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="300" timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
To understand more, read this official ehcache.xml example.
package com.mkyong.cache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class HelloEhCache{
public static void main(String[] args) {
//1. Create a cache manager
CacheManager cm = CacheManager.newInstance();
//cm.addCache("cache1");
//2. Get a cache called "cache1", declared in ehcache.xml
Cache cache = cm.getCache("cache1");
//3. Put few elements in cache
cache.put(new Element("1","Jan"));
cache.put(new Element("2","Feb"));
cache.put(new Element("3","Mar"));
//4. Get element from cache
Element ele = cache.get("2");
//5. Print out the element
String output = (ele == null ? null : ele.getObjectValue().toString());
System.out.println(output);
//6. Is key in cache?
System.out.println(cache.isKeyInCache("3"));
System.out.println(cache.isKeyInCache("10"));
//7. shut down the cache manager
cm.shutdown();
}
}
Output
06:45:56.294 [main] DEBUG n.s.e.config.ConfigurationFactory -
Configuring ehcache from ehcache.xml found in the classpath:
file:/C:/Users/mkyong/workspace2/JavaCache/target/classes/ehcache.xml
//...
Feb
true
false
//...
More info about Loading a Configuration
I ran into the problem:
Error: Could not find or load main class com.mkyong.cache.JavaEhCache
Do you have any hint to fix that?
Hi,
I am getting So DEBUG logs in my logs file I want to turn them of Can you please help me.
I reckon that in your first example: “String output = (ele == null ? null : ele.getObjectValue().toString());” should probably read: “String output = (ele == null ? “” : ele.getObjectValue().toString());”
How about an example on how to synchronize the Ehcache and the datastore?
Thanks.