使用ehcache

openkk 12年前
      一直以来懒得配置缓存,基本的缓存也就是orm层,基本上都交给hibernate去配置了。这段时间,感觉页面速度太慢了,还是需要使用缓存。现在的缓存工具也挺多的,较不错的属ehcache和oscache了。决定分别研究一下。    <br />     先来说说ehcache,目前的版本为1.2,已经支持集群了。对于ehcache的使用,感觉很容易上手,基本上都是配置。以前在hibernate的时候配置过,所以也不是很陌生。API也挺简单,如下的api:    <br />     CacheManager主要的缓存管理类,一般一个应用为一个实例,如下    <br />     CacheManager.create();也可以使用new CacheManager的方式创建    <br />      默认的配置文件为ehcache.xml文件,也可以使用不同的配置:    <br />          <br />      <br /> CacheManager manager = new CacheManager("src/config/other.xml");        <br />    <br />    <strong>缓存的创建,采用自动的方式</strong>    <br />      <br /> CacheManager singletonManager = CacheManager.create();    <br /> singletonManager.addCache("testCache");    <br /> Cache test = singletonManager.getCache("testCache");        <br />    <strong><br /> 或者直接创建Cache</strong>    <br />      <br /> CacheManager singletonManager = CacheManager.create();    <br /> Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);    <br /> manager.addCache(memoryOnlyCache);    <br /> Cache test = singletonManager.getCache("testCache");        <br />    <br />    <strong>删除cache</strong>    <br />      <br /> CacheManager singletonManager = CacheManager.create();    <br /> singletonManager.removeCache("sampleCache1");        <br />    <br />    <strong>在使用ehcache后,需要关闭</strong>    <br />      <br /> CacheManager.getInstance().shutdown()        <br />    <strong><br /> caches 的使用</strong>    <br />      <br /> Cache cache = manager.getCache("sampleCache1");        <br />    <strong><br /> 执行crud操作</strong>    <br />      <br /> Cache cache = manager.getCache("sampleCache1");    <br /> Element element = new Element("key1", "value1");    <br /> cache.put(element);        <br />    <br />    <strong>update</strong>    <br />      <br /> Cache cache = manager.getCache("sampleCache1");    <br /> cache.put(new Element("key1", "value1");    <br /> //This updates the entry for "key1"    <br /> cache.put(new Element("key1", "value2");        <br />    <strong><br /> get Serializable</strong>    <br />      <br /> Cache cache = manager.getCache("sampleCache1");    <br /> Element element = cache.get("key1");    <br /> Serializable value = element.getValue();        <br />    <br />    <strong>get non serializable</strong>    <br />      <br /> Cache cache = manager.getCache("sampleCache1");    <br /> Element element = cache.get("key1");    <br /> Object value = element.getObjectValue();        <br />    <br />    <strong>remove</strong>    <br />      <br /> Cache cache = manager.getCache("sampleCache1");    <br /> Element element = new Element("key1", "value1"    <br /> cache.remove("key1");        <br />    <br /> 不过缓存还是基本上以配置方式为主,下一篇文章将会说明ehcache如何配置    <br />