分享

使用ehcache

 CevenCheng 2012-04-18
  一直以来懒得配置缓存,基本的缓存也就是orm层,基本上都交给hibernate去配置了。这段时间,感觉页面速度太慢了,还是需要使用缓存。现在的缓存工具也挺多的,较不错的属ehcache和oscache了。决定分别研究一下。
    先来说说ehcache,目前的版本为1.2,已经支持集群了。对于ehcache的使用,感觉很容易上手,基本上都是配置。以前在hibernate的时候配置过,所以也不是很陌生。API也挺简单,如下的api:
    CacheManager主要的缓存管理类,一般一个应用为一个实例,如下
    CacheManager.create();也可以使用new CacheManager的方式创建
     默认的配置文件为ehcache.xml文件,也可以使用不同的配置:
     
java 代码
 
  1.    
  2. CacheManager manager = new CacheManager("src/config/other.xml");  
    

缓存的创建,采用自动的方式
java 代码
 
  1.    
  2. CacheManager singletonManager = CacheManager.create();  
  3. singletonManager.addCache("testCache");  
  4. Cache test = singletonManager.getCache("testCache");      

或者直接创建Cache

java 代码
 
  1.    
  2. CacheManager singletonManager = CacheManager.create();  
  3. Cache memoryOnlyCache = new Cache("testCache"5000falsefalse52);  
  4. manager.addCache(memoryOnlyCache);  
  5. Cache test = singletonManager.getCache("testCache");      

删除cache
 
java 代码
 
  1. CacheManager singletonManager = CacheManager.create();  
  2. singletonManager.removeCache("sampleCache1");    
  

在使用ehcache后,需要关闭
 
java 代码
 
  1. CacheManager.getInstance().shutdown()      
  2.   
  3. caches 的使用  
  4.    
  5. Cache cache = manager.getCache("sampleCache1");       


执行crud操作

 
java 代码
 
  1. Cache cache = manager.getCache("sampleCache1");  
  2. Element element = new Element("key1""value1");  
  3. cache.put(element);      
  4.   
  5. update  
  6.    
  7. Cache cache = manager.getCache("sampleCache1");  
  8. cache.put(new Element("key1""value1");  
  9. //This updates the entry for "key1"  
  10. cache.put(new Element("key1""value2");      
  11.   
  12. get Serializable  
  13.    
  14. Cache cache = manager.getCache("sampleCache1");  
  15. Element element = cache.get("key1");  
  16. Serializable value = element.getValue();      
  17.   
  18. get non serializable  
  19.    
  20. Cache cache = manager.getCache("sampleCache1");  
  21. Element element = cache.get("key1");  
  22. Object value = element.getObjectValue();      
  23.   
  24. remove  
  25.    
  26. Cache cache = manager.getCache("sampleCache1");  
  27. Element element = new Element("key1""value1"  
  28. cache.remove("key1");      


不过缓存还是基本上以配置方式为主,下一篇文章将会说明ehcache如何配置
    

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多