EHCache入门系列(二)–在工程中单独使用

 
1.创建CacheManager (net.sf.ehcache.CacheManager)

(1)使用默认配置文件创建

CacheManager manager = CacheManager.create();

(2)使用指定配置文件创建

CacheManager manager = CacheManager.create("src/config/ehcache.xml");

(3)从classpath找寻配置文件并创建

URL url = getClass().getResource("/anothername.xml");

CacheManager manager = CacheManager.create(url);

(4)通过输入流创建

InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());

try { manager = CacheManager.create(fis); } finally { fis.close(); }

2.创建Caches (net.sf.ehcache.Cache)

(1)取得配置文件中预先 定义的sampleCache1设置,生成一个Cache

Cache cache = manager.getCache("sampleCache1");

(2)设置一个名为test 的新cache,test属性为默认

CacheManager manager = CacheManager.create();

manager.addCache("test");

(3)设置一个名为test 的新cache,并定义其属性

CacheManager manager = CacheManager.create();

Cache cache = new Cache("test", 1, true, false, 5, 2);

manager.addCache(cache);

(4)删除cache

CacheManager singletonManager = CacheManager.create();

singletonManager.removeCache("sampleCache1"); 

3.使用Caches

(1)往cache中加入元素

Element element = new Element("key1", "value1");

cache.put(new Element(element);

(2)从cache中取得元素

Element element = cache.get("key1");

(3)从cache中删除元素

Cache cache = manager.getCache("sampleCache1");

Element element = new Element("key1", "value1");

cache.remove("key1"); 

3.卸载CacheManager ,关闭Cache

manager.shutdown();

你可能感兴趣的:(EHCache入门系列(二)–在工程中单独使用)