EhCache 實例代碼
EhcacheUtil,可以實例模式也可以單例模式,我都寫好了,可以試下
package com.util;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class EhcacheUtil {
private Cache cache;
private void loadPrame() {
/**
* 單例模式
*/
try {
CacheManager.create("src/com/x/ehcache.xml");
cache = CacheManager.getInstance().getCache("a");
PrameUtil pUtil = new PrameUtil();
for (int i = 0; i < 6; i++) {
cache.put(new Element(String.valueOf(i), pUtil.getPrame(String.valueOf(i))));
}
} catch (CacheException e1) {
e1.printStackTrace();
}
// /**
// * 實例
// */
// try {
// CacheManager cm = CacheManager.create("src/com/x/ehcache.xml");
// // cache = new Cache("b", 5000, false, false, 5, 2);
// // cm.addCache(cache);
// // cache = cm.getCache("b");
// cache = cm.getCache("a");
// PrameUtil pUtil = new PrameUtil();
// for (int i = 1; i < 6; i++) {
// cache.put(new Element(String.valueOf(i), pUtil.getPrame(String
// .valueOf(i))));
// }
// } catch (IllegalStateException e) {
// e.printStackTrace();
// } catch (CacheException e) {
// e.printStackTrace();
// }
}
public String getPrame(String key) {
String value = "";
try {
if (cache == null) {
loadPrame();
}
Element el = cache.get((String) key);
if (el == null) {
loadPrame();
el = cache.get((String) key);
}
if (el == null) {
System.out.println("沒有");
}
value = el.getValue().toString();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (CacheException e) {
e.printStackTrace();
}
return value;
}
}PrameUtil,這個類是讀取properties文件的,很簡單,用到InputStream is = this.getClass().getClassLoader().getResourceAsStream("com/p/p.properties");
package com.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PrameUtil {
public String getPrame(String key){
String value = "";
InputStream is = this.getClass().getClassLoader().getResourceAsStream("com/p/p.properties");
System.out.println(this.getClass().getClassLoader());
System.out.println(this.getClass().getClassLoader().getResourceAsStream(""));
Properties p = new Properties();
try {
p.load(is);
value = p.getProperty(key);
} catch (IOException e) {
e.printStackTrace();
}
return value;
}
}測試類TestMain,更簡單,都不好意思貼出來
public class TestMain {
public static void main(String[] args) {
EhcacheUtil eUtil = new EhcacheUtil();
String one = eUtil.getPrame("1");
System.out.println(one);
}
}ehcache.xml文件內容如下,記得放好位置
<ehcache>
<defaultCache maxElementsInMemory="1000" eternal="true"
timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" />
<cache name="a" maxElementsInMemory="1000" eternal="true"
timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="false" />
</ehcache>轉自:http://blog.csdn.net/liuxiaochen123/article/details/7823089
本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!