如果找到了对您有用的资料,烦请点击右手边的Google广告支持我继续共享知识,谢谢! http://dengpeng.spaces.live.com/

2008年12月24日星期三

Simple EHCACHE Application

Ehcache is a widely used java distributed cache for general purpose caching, Java EE and light-weight containers.
It features memory and disk stores, replicate by copy and invalidate, listeners, cache loaders, cache extensions, cache exception handlers, a gzip caching servlet filter and much more ...
Ehcache is available under an Apache open source license and is actively developed, maintained and supported.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package helloehcache;

import java.util.Random;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
*
* @author Administrator
*/

public class Main {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
//Create a CacheManager instance using defaults.
CacheManager manager = new CacheManager();
//Create a Cache and add it to the CacheManager, then use it.
/*
* @param name the name of the cache. Note that "default" is a reserved name for the defaultCache.
* @param maxElementsInMemory the maximum number of elements in memory, before they are evicted
* @param overflowToDisk whether to use the disk store
* @param eternal whether the elements in the cache are eternal, i.e. never expire
* @param timeToLiveSeconds the default amount of time to live for an element from its creation date
* @param timeToIdleSeconds the default amount of time to live for an element from its last accessed or modified date
*/

Cache memoryOnlyCache = new Cache("CacheName", 5000, true, false, 7, 2);
manager.addCache(memoryOnlyCache);
Cache testCache = manager.getCache("CacheName");

for (int i = 0; i < 10; i++) {
//Queries are coming
Random random = new Random();
String key = "Key" + String.valueOf((int) (random.nextFloat() * 10f));
String value = "Value" + String.valueOf(random.nextFloat() * 10f);
System.out.println(i + ". Quering " + key);
if (testCache.get(key) == null) {
System.out.print("Cache is not hit! ");
testCache.put(new Element(key, value));
System.out.print(key + " " + value + " has been put into cache.");
} else {
System.out.print("Cache is hit! ");
Element cachedResult = testCache.get(key);
System.out.print("The value is " + cachedResult.getObjectValue());
}
System.out.println();
System.out.println();
}
System.out.println(testCache.getStatistics().getCacheMisses() + "/10 missing");
manager.shutdown();
}
}


For more code samples, please visit: http://ehcache.sourceforge.net/documentation/samples.html

没有评论: