EhCacheUtilキャッシュツールクラス
17911 ワード
/**
* API ( java )
*
* @author Administrator
*/
public class EhCacheUtil {
private static Logger logger = LoggerFactory.getLogger(EhCacheUtil.class);
private static CacheManager singletonManager;
private static String proName;
private static int maxElementsInMemory;
private static Boolean overflowToDisk;
private static boolean eternal;
private static long timeToLiveSeconds;
private static long timeToIdleSeconds;
static {
singletonManager = CacheManager.create();
Properties properties = new Properties();
// ClassLoader properties
InputStream in = EhCacheUtil.class.getClassLoader().getResourceAsStream("ehcache.properties");
// properties
try {
properties.load(in);
proName = Globals.APP_BASE_NAME.replace("/","");
maxElementsInMemory = Integer.parseInt(properties.getProperty("MAXELEMENTSINMEMORY"));
overflowToDisk = Boolean.parseBoolean(properties.getProperty("OVERFLOWTODISK"));
eternal = Boolean.parseBoolean(properties.getProperty("ETERNAL"));
timeToLiveSeconds = Long.parseLong(properties.getProperty("TIMETOLIVESECONDS"));
timeToIdleSeconds = Long.parseLong(properties.getProperty("TIMETOIDLESECONDS"));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
*/
public static void createCache() {
Cache memoryOnlyCache = singletonManager.getCache(proName);
//
if (memoryOnlyCache == null) {
//
memoryOnlyCache = new Cache(proName, maxElementsInMemory, overflowToDisk, eternal, timeToLiveSeconds, timeToIdleSeconds);
//
singletonManager.addCache(memoryOnlyCache);
}
logger.info(" ->"+proName+" !");
}
/**
*
*
* @param key
* @return
*/
@SuppressWarnings("deprecation")
public static Object getValue(String key) {
//
Cache cache = singletonManager.getCache(proName);
Element element = cache.get(key);
if (element == null) {
return null;
}
return element.getValue();
}
/**
*
*
* @param key
* @param value
*/
public static void setValue(String key, Object value) {
Cache cache = singletonManager.getCache(proName);
//
Element element = new Element(key, value);
cache.put(element);//
}
/**
*
*
* @param key
*/
public static void remove(String key) {
Cache cache = singletonManager.getCache(proName);
Element element = cache.get(key);
if (element != null) {
cache.remove(key);
}
}
/**
*
*
* @param key
*/
public static boolean isEmpty(String key) {
Cache cache = singletonManager.getCache(proName);
Element element = cache.get(key);
if (element != null) {
return false;
}
return true;
}
}
ehcache.properties
#
MAXELEMENTSINMEMORY=1000
#
OVERFLOWTODISK=false
#
ETERNAL=false
#
TIMETOLIVESECONDS=7200
#
TIMETOIDLESECONDS=7200