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();
InputStream in = EhCacheUtil.class.getClassLoader().getResourceAsStream("ehcache.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+"库创建成功!");
}
@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();
}
public static void setValue(String key, Object value) {
Cache cache = singletonManager.getCache(proName);
Element element = new Element(key, value);
cache.put(element);
}
public static void remove(String key) {
Cache cache = singletonManager.getCache(proName);
Element element = cache.get(key);
if (element != null) {
cache.remove(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