EhCache缓存在web下的使用实例

以前对EhCache做过api的学习与测试,api就不多讲了,这次把在web下如何使用EhCache以及出现的问题说一下。

同时这篇还写了EhCache的监听。


在web下使用缓存,就是把常用的变动很少的数据放入缓存提高查询效率。如果需要查看实时的数据,需要把缓存清空再查询。

比如有一张字典表,定义了整个工程使用到了配置信息,这个基本上是不变的,所以可以用缓存来提高查询效率。


Dictionary,值得注意的是要实现Serializable接口,因为缓存可能要往硬盘写对象。

[java]  view plain copy
  1. package org.base.common.dictionary.bean;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Date;  
  5.   
  6. /** 
  7.  * 公用的字典表对象 
  8.  * @author blossom 
  9.  * 
  10.  */  
  11. public class Dictionary  implements Serializable{  
  12.     /** 
  13.      * 需要implements Serializable,因为ehcache需要往硬盘写对象 
  14.      */  
  15.     private static final long serialVersionUID = 1L;  
  16.       
  17.     private String id;  
  18.     private String code_no;  
  19.     private String code_name;  
  20.     private String code_parent_no;  
  21.     private int show_order;  
  22.     private Date create_time;  
  23.     private String remark;  
  24.     private String create_user;  
  25.     private String valid;  
  26.     private String bak1;  
  27.     private String bak2;  
  28.     private String bak3;  
  29.       
  30.     public String getId() {  
  31.         return id;  
  32.     }  
  33.     public void setId(String id) {  
  34.         this.id = id;  
  35.     }  
  36.     public String getCode_no() {  
  37.         return code_no;  
  38.     }  
  39.     public void setCode_no(String code_no) {  
  40.         this.code_no = code_no;  
  41.     }  
  42.     public String getCode_name() {  
  43.         return code_name;  
  44.     }  
  45.     public void setCode_name(String code_name) {  
  46.         this.code_name = code_name;  
  47.     }  
  48.     public String getCode_parent_no() {  
  49.         return code_parent_no;  
  50.     }  
  51.     public void setCode_parent_no(String code_parent_no) {  
  52.         this.code_parent_no = code_parent_no;  
  53.     }  
  54.     public int getShow_order() {  
  55.         return show_order;  
  56.     }  
  57.     public void setShow_order(int show_order) {  
  58.         this.show_order = show_order;  
  59.     }  
  60.     public Date getCreate_time() {  
  61.         return create_time;  
  62.     }  
  63.     public void setCreate_time(Date create_time) {  
  64.         this.create_time = create_time;  
  65.     }  
  66.     public String getRemark() {  
  67.         return remark;  
  68.     }  
  69.     public void setRemark(String remark) {  
  70.         this.remark = remark;  
  71.     }  
  72.     public String getCreate_user() {  
  73.         return create_user;  
  74.     }  
  75.     public void setCreate_user(String create_user) {  
  76.         this.create_user = create_user;  
  77.     }  
  78.     public String getValid() {  
  79.         return valid;  
  80.     }  
  81.     public void setValid(String valid) {  
  82.         this.valid = valid;  
  83.     }  
  84.     public String getBak1() {  
  85.         return bak1;  
  86.     }  
  87.     public void setBak1(String bak1) {  
  88.         this.bak1 = bak1;  
  89.     }  
  90.     public String getBak2() {  
  91.         return bak2;  
  92.     }  
  93.     public void setBak2(String bak2) {  
  94.         this.bak2 = bak2;  
  95.     }  
  96.     public String getBak3() {  
  97.         return bak3;  
  98.     }  
  99.     public void setBak3(String bak3) {  
  100.         this.bak3 = bak3;  
  101.     }  
  102.       
  103.   
  104. }  

同时我定义了一个MyCacheObject用于公用的实现了Serializable
[java]  view plain copy
  1. package org.base.cache;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import net.sf.ehcache.CacheEntry;  
  6. import net.sf.ehcache.Element;  
  7.   
  8. /** 
  9.  *  
  10.  * @author blossom 
  11.  * 
  12.  */  
  13. public class MyCacheObject implements Serializable{  
  14.     private static final long serialVersionUID = 1L;  
  15.     public Object object;  
  16.   
  17.     public Object getObject() {  
  18.         return object;  
  19.     }  
  20.   
  21.     public void setObject(Object object) {  
  22.         this.object = object;  
  23.     }  
  24.       
  25.     public MyCacheObject(){}  
  26.     public MyCacheObject(Object object){  
  27.         this.object=(Serializable)object;  
  28.     }  
  29.       
  30.       
  31.   
  32. }  


配置文件ehcache.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.          xsi:noNamespaceSchemaLocation="ehcache.xsd"  
  4.          updateCheck="true" monitoring="autodetect"  
  5.          dynamicConfig="true">  
  6.   
  7.       
  8.     <diskStore path="java.io.tmpdir"/>  
  9.       
  10.     <!-- JTA事务配置。class属性若为空,则默认会按照一个顺序寻找TransactionManager对象。  
  11.               也可以自定义,需要实现接口net.sf.ehcache.transaction.manager.TransactionManagerLookup  
  12.     -->  
  13.     <!--  
  14.     <transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"  
  15.                               properties="jndiName=java:/TransactionManager" propertySeparator=";"/>  
  16.     -->  
  17.   
  18.     <!-- CacheManagerEventListener  缓存监听,根据需要自定义监听类-->   
  19.     <cacheManagerEventListenerFactory class="org.base.cache.MyCacheManagerEventListener" />  
  20.       
  21.       
  22.     <!-- Terracotta服务器集群配置,详细看文档 -->  
  23.     <!-- 
  24.     <terracottaConfig url="localhost:9510"/> 
  25.     -->  
  26.       
  27.     <defaultCache  
  28.            maxEntriesLocalHeap="10000"  
  29.            maxEntriesLocalDisk="20000"  
  30.            eternal="false"  
  31.            diskSpoolBufferSizeMB="20"  
  32.            overflowToDisk="true"  
  33.            diskPersistent="true"  
  34.            timeToIdleSeconds="30"  
  35.            timeToLiveSeconds="30">  
  36.      <!-- <terracotta/>-->  
  37.     </defaultCache>  
  38.   
  39.     <!--  
  40.            缓存名为myCommonCache,  
  41.     这个缓存最多包含10000个元素在内存中,并将  
  42.     闲置超过5分钟和存在超过10分钟的元素释放。  
  43.     如果超过10000元素,将溢流到磁盘缓存,并且硬盘缓存最大数量是1000.  
  44.            硬盘路径是定义的java.io.tmp。  
  45.     -->  
  46.     <cache name="myCommonCache"  
  47.            maxEntriesLocalHeap="500"  
  48.            maxEntriesLocalDisk="1000"  
  49.            eternal="false"  
  50.            diskSpoolBufferSizeMB="20"  
  51.            timeToIdleSeconds="15"  
  52.            timeToLiveSeconds="30"  
  53.            memoryStoreEvictionPolicy="LFU"  
  54.            transactionalMode="off">  
  55.         <persistence strategy="localTempSwap"/>  
  56.     </cache>  
  57.   
  58.   
  59.     <!--  
  60.             缓存名为sampleCache2。  
  61.     此缓存在内存中最大元素的数量是1000。  
  62.             没有设置溢出到磁盘,所以1000就是这个缓存的最大值。  
  63.             注意,当一个缓存eternal设置成true,那么TimeToLive  
  64.     和timeToIdle江不起作用。  
  65.       
  66.     <cache name="sampleCache2"  
  67.            maxEntriesLocalHeap="1000"  
  68.            eternal="true"  
  69.            memoryStoreEvictionPolicy="FIFO"/>  
  70. -->  
  71.   
  72.     <!--   
  73.            缓存名为sampleCache3的。  
  74.            这个缓存溢出会到磁盘。磁盘缓存存储在虚拟机重新启动前会持久有效。  
  75.            磁盘的终止线程的时间间隔设置为3分钟,覆盖默认的2分钟。  
  76.        
  77.     <cache name="sampleCache3"  
  78.            maxEntriesLocalHeap="500"  
  79.            eternal="false"  
  80.            overflowToDisk="true"  
  81.            diskPersistent="true"  
  82.            timeToIdleSeconds="300"  
  83.            timeToLiveSeconds="600"  
  84.            diskExpiryThreadIntervalSeconds="180"  
  85.            memoryStoreEvictionPolicy="LFU">  
  86.     </cache>  
  87. -->  
  88.       
  89.       
  90. </ehcache>  


缓存管理类MyEhcacheManager

[java]  view plain copy
  1. package org.base.cache;  
  2.   
  3. import java.io.Serializable;  
  4. import java.net.URL;  
  5. import java.util.List;  
  6.   
  7. import org.base.cache.dao.MyEhcacheDao;  
  8.   
  9. import net.sf.ehcache.Cache;  
  10. import net.sf.ehcache.CacheEntry;  
  11. import net.sf.ehcache.CacheManager;  
  12. import net.sf.ehcache.Element;  
  13. import net.sf.ehcache.Status;  
  14.   
  15. /** 
  16.  * Ehcache缓存管理在web下的使用实例 
  17.  * @author blossom 
  18.  * 
  19.  */  
  20. public class MyEhcacheManager {  
  21.     public static net.sf.ehcache.CacheManager cacheManager = null;  
  22.     private static String configPath="/ehcache.xml";//配置文件  
  23.     private MyEhcacheDao myEhcacheDao;//查询  
  24.       
  25.     //缓存定义  
  26.     private static String CACHE_MYCOMMONCACHE="myCommonCache";//定义文件中配置的缓存  
  27.       
  28.     //缓存中的Element定义  
  29.     private static String ELEMENT_MYCOMMONCACHE_DICTIONARY="dictionaryList";//缓存元素   
  30.       
  31.       
  32.     //实例化cacheManager,单例模式  
  33.     public static CacheManager getCacheManagerInstance(){  
  34.         if (cacheManager == null) {  
  35.             URL configUrl=null;  
  36.             configUrl = MyEhcacheManager.class.getClassLoader().getResource(configPath);  
  37.             cacheManager = CacheManager.create(configUrl);  
  38.         }  
  39.         return cacheManager;  
  40.     }  
  41.     public static net.sf.ehcache.CacheManager getCacheManager() {  
  42.         return getCacheManagerInstance();//单例缓存管理  
  43.     }  
  44.       
  45.     public static void setCacheManager(net.sf.ehcache.CacheManager cacheManager) {  
  46.         MyEhcacheManager.cacheManager = cacheManager;  
  47.     }  
  48.       
  49.     //添加新缓存  
  50.     public static void addCacheByName(String cacheName){  
  51.         if(cacheName==null||cacheName.trim().equals("")){  
  52.             System.out.println("cacheName is null");  
  53.         }else{  
  54.             if(getCacheManager().getCache(cacheName.trim())!=null){  
  55.                 getCacheManager().removeCache(cacheName.trim());  
  56.             }  
  57.             getCacheManager().addCache(cacheName.trim());  
  58.             System.out.println(cacheName+ "重新添加");  
  59.         }  
  60.     }  
  61.     //得到cache对象  
  62.     public static Cache getCacheByName(String cacheName){  
  63.         Cache cache=null;  
  64.         if(cacheName==null||cacheName.trim().equals("")){  
  65.             System.out.println("cacheName is null");  
  66.         }else{  
  67.             if(getCacheManager().getCache(cacheName.trim())!=null){  
  68.                 cache=getCacheManager().getCache(cacheName.trim());  
  69.             }  
  70.         }  
  71.           
  72.         return cache;  
  73.     }  
  74.       
  75.       
  76.     //往缓存中添加元素  
  77.     public static void putElementToCache(String cacheName,String elementKey,Object elementValue){  
  78.         Cache cache=null;  
  79.         if(cacheName==null||cacheName.trim().equals("")){  
  80.             System.out.println("添加缓存元素失败,cacheName is null");  
  81.         }else if(elementKey==null||elementValue==null){  
  82.             System.out.println("添加缓存元素失败,elementKey or elementValue is null");  
  83.         }else{  
  84.             if(getCacheByName(cacheName.trim())!=null){//缓存存在  
  85.                 cache=getCacheByName(cacheName.trim());  
  86.             }else{//缓存不存在  
  87.                 addCacheByName(cacheName.trim());  
  88.                 cache=getCacheByName(cacheName.trim());  
  89.             }  
  90.             //对cache对象添加Element  
  91.             Element element=null;  
  92.             if(cache.get(elementKey.trim())!=null){  
  93.                 cache.remove(elementKey.trim());  
  94.             }  
  95.             element=new Element(elementKey.trim(),elementValue);  
  96.             cache.put(element);  
  97.             System.out.println("添加缓存元素:"+elementKey+"成功!");  
  98.         }  
  99.           
  100.     }  
  101.       
  102.     //从缓存中获取指定key的值  
  103.     public static Object getElementValueFromCache(String cacheName,String elementKey){  
  104.         Object result=null;  
  105.         Cache cache=null;  
  106.         if(cacheName==null||cacheName.trim().equals("")){  
  107.             System.out.println("获取缓存元素失败,cacheName is null");  
  108.         }else if(elementKey==null){  
  109.             System.out.println("获取缓存元素失败,elementKey  is null");  
  110.         }else{  
  111.             if(getCacheByName(cacheName.trim())!=null){//缓存存在  
  112.                 cache=getCacheByName(cacheName.trim());  
  113.                   
  114.                 Element element=null;  
  115.                 if(cache.get(elementKey.trim())!=null){  
  116.                     element=cache.get(elementKey.trim());  
  117.                     if(element.getObjectValue()==null){  
  118.                         System.out.println("缓存中"+elementKey+" 的值为空.");  
  119.                     }else{  
  120.                         result=element.getObjectValue();  
  121.                     }  
  122.                 }else{  
  123.                     System.out.println("缓存中"+elementKey+" 的Element值为空.");  
  124.                 }  
  125.             }else{//缓存不存在  
  126.                 System.out.println("获取缓存元素失败,缓存"+cacheName+" 为空.");  
  127.             }  
  128.         }  
  129.           
  130.         return result;  
  131.     }  
  132.       
  133.     /** 
  134.      * 把所有cache中的内容删除,但是cache对象还是保留. 
  135.      * Clears the contents of all caches in the CacheManager, 
  136.      *  but without removing any caches. 
  137.      */  
  138.     public static void clearAllFromCacheManager(){  
  139.         if(getCacheManager()!=null){  
  140.             getCacheManager().clearAll();  
  141.             System.out.println("CacheManager was clearAll...");  
  142.         }  
  143.     }   
  144.       
  145.     /** 
  146.      * 把所有cache对象都删除。慎用! 
  147.      * Removes all caches using removeCache(String) for each cache. 
  148.      */  
  149.     public static void removalAllFromCacheManager(){  
  150.         if(getCacheManager()!=null){  
  151.             getCacheManager().removalAll();  
  152.             System.out.println("CacheManager was removalAll...");  
  153.         }  
  154.     }   
  155.     //不用缓存时,要关闭,不然会占用cpu和内存资源。  
  156.     public static void shutdownCacheManager(){  
  157.         if(getCacheManager()!=null){  
  158.             getCacheManager().shutdown();  
  159.             System.out.println("CacheManager was shutdown...");  
  160.         }  
  161.     }  
  162.       
  163.       
  164.     //打印方法1,为了测试用  
  165.     public static void printCache(Cache cache){  
  166.         System.out.println("缓存状态: "+cache.getStatus().toString());  
  167.         if(cache==null){  
  168.             System.out.println("cache is null,no print info.");  
  169.         }else if(cache.getStatus().toString().equals(Status.STATUS_UNINITIALISED)){  
  170.             System.out.println("缓存状态: 未初始化"+cache.getStatus().toString());  
  171.         }else if(cache.getStatus().toString().equals(Status.STATUS_SHUTDOWN)){  
  172.             System.out.println("缓存状态: 已关闭"+cache.getStatus().toString());  
  173.         }else if(cache.getStatus().toString().equals(Status.STATUS_ALIVE)){  
  174.             if(cache.getKeys().size()==0){  
  175.                 System.out.println(cache.getName()+" exits,but no value.");  
  176.             }else{  
  177.                 for(int i=0;i<cache.getKeys().size();i++){  
  178.                     Object thekey=cache.getKeys().get(i);  
  179.                     Object thevalue=cache.get(thekey);  
  180.                     System.out.println(cache.getName()+"--"+i+",key:"+thekey.toString()+",value:"+thevalue.toString());  
  181.                 }  
  182.             }  
  183.         }  
  184.           
  185.           
  186.     }  
  187.       
  188.     //打印方法2,为了测试用  
  189.     public static void printCacheByName(String cacheName){  
  190.         if(cacheName==null||cacheName.trim().equals("")){  
  191.             System.out.println("cacheName is null,no print info.");  
  192.         }else{  
  193.             if(getCacheManager().getCache(cacheName.trim())!=null){  
  194.                 Cache cache=getCacheManager().getCache(cacheName.trim());  
  195.                 printCache(cache);  
  196.             }else{  
  197.                 System.out.println(cacheName+" --null");  
  198.             }  
  199.         }  
  200.           
  201.           
  202.     }  
  203.       
  204.     public static void main(String[] sdfsf){  
  205.         Cache cache1=MyEhcacheManager.getCacheByName(MyEhcacheManager.CACHE_MYCOMMONCACHE);  
  206.         printCache(cache1);  
  207.           
  208.         MyEhcacheManager.putElementToCache(MyEhcacheManager.CACHE_MYCOMMONCACHE, "111""111haah");  
  209.         MyEhcacheManager.putElementToCache(MyEhcacheManager.CACHE_MYCOMMONCACHE, "222""222haah");  
  210.         MyEhcacheManager.putElementToCache(MyEhcacheManager.CACHE_MYCOMMONCACHE, "333""333haah");  
  211.           
  212.         printCache(cache1);  
  213.           
  214.         MyEhcacheManager.putElementToCache(MyEhcacheManager.CACHE_MYCOMMONCACHE, "111""111的新值。");  
  215.           
  216.         System.out.println(MyEhcacheManager.getElementValueFromCache(MyEhcacheManager.CACHE_MYCOMMONCACHE, "111"));  
  217.         printCache(cache1);  
  218.           
  219.         clearAllFromCacheManager();  
  220.         printCache(cache1);  
  221.           
  222.         removalAllFromCacheManager();  
  223.         printCache(cache1);  
  224.           
  225.         shutdownCacheManager();  
  226.     }  
  227.     /*打印 
  228. 缓存状态: STATUS_ALIVE 
  229. 添加缓存元素:111成功! 
  230. 添加缓存元素:222成功! 
  231. 添加缓存元素:333成功! 
  232. 缓存状态: STATUS_ALIVE 
  233. 添加缓存元素:111成功! 
  234. 111的新值。 
  235. 缓存状态: STATUS_ALIVE 
  236. CacheManager was clearAll... 
  237. 缓存状态: STATUS_ALIVE 
  238. CacheManager was removalAll... 
  239. 缓存状态: STATUS_SHUTDOWN 
  240. CacheManager was shutdown... 
  241.  
  242.      */  
  243.     public MyEhcacheDao getMyEhcacheDao() {  
  244.         return myEhcacheDao;  
  245.     }  
  246.     public void setMyEhcacheDao(MyEhcacheDao myEhcacheDao) {  
  247.         this.myEhcacheDao = myEhcacheDao;  
  248.     }  
  249.     ///上面是对缓存操作的Demo,实际使用逻辑需要改变 /  
  250.       
  251.       
  252.       
  253.       
  254.     ///以下是web环境下对字典表的缓存操作/  
  255.       
  256.     //得到字典表cache对象("myCommonCache")  
  257.     public Cache getMyCommonCache(){  
  258.         Cache cache=null;  
  259.         if(getCacheManager().getCache(MyEhcacheManager.CACHE_MYCOMMONCACHE)!=null){  
  260.             cache=getCacheManager().getCache(MyEhcacheManager.CACHE_MYCOMMONCACHE);  
  261.         }else{//如果缓存没有了,这里直接添加,因为在实际中我们不可能告诉应用没有了这个缓存就返回了。  
  262.             //而是应该先去查数据,放入缓存,然后再从缓存中取数据。  
  263.             //当然,如果缓存有数据,那就直接取数据就行了。  
  264.             getCacheManager().addCache(MyEhcacheManager.CACHE_MYCOMMONCACHE);  
  265.         }  
  266.         return cache;  
  267.     }  
  268.       
  269.     //从mycommon缓存中获取字典表数据(这里只是简单的把所有值取出来了,实际应用可以更加细化)  
  270.     public List getDictionaryListFromMyCommonCache(String codeNo){  
  271.         codeNo=(codeNo==null||codeNo.trim().equals(""))?"":codeNo.trim();  
  272.         List dictionaryList=null;  
  273.         Cache cache=getMyCommonCache();//字典表公用缓存  
  274.         Element element=null;  
  275.         if(cache.get(MyEhcacheManager.ELEMENT_MYCOMMONCACHE_DICTIONARY)!=null){  
  276.             element=cache.get(MyEhcacheManager.ELEMENT_MYCOMMONCACHE_DICTIONARY);  
  277.               
  278.             if(element.getObjectValue()==null){//值为空,需要从新添加到缓存  
  279.                 List list=this.getMyEhcacheDao().querydictionaryByCodeNo(codeNo);//查询  
  280.                 if(list!=null){  
  281.                     MyCacheObject myCacheObject = new MyCacheObject(list);  
  282.                     element=new Element((Serializable)MyEhcacheManager.ELEMENT_MYCOMMONCACHE_DICTIONARY,(Serializable)myCacheObject);  
  283.                     //java.io.NotSerializableException:  
  284.                     cache.put(element);  
  285.                     System.out.println("缓存中的字典表元素为空,重新查询添加..");  
  286.                 }  
  287.                 dictionaryList=list;  
  288.             }else{//有值  
  289.                 MyCacheObject myObj=(MyCacheObject)element.getObjectValue();  
  290.                 dictionaryList=(List)myObj.getObject();  
  291.                 System.out.println("缓存中存在字典表数据,直接获取到。");  
  292.             }  
  293.         }else{//获取Element空,需要从新添加到缓存  
  294.             List list=this.getMyEhcacheDao().querydictionaryByCodeNo("");//查询  
  295.             if(list!=null){  
  296.                 MyCacheObject myCacheObject = new MyCacheObject(list);  
  297.                 element=new Element((Serializable)MyEhcacheManager.ELEMENT_MYCOMMONCACHE_DICTIONARY,(Serializable)myCacheObject);  
  298.                 cache.put(element);  
  299.                 System.out.println("缓存中的字典表元素为空,重新查询添加......");  
  300.             }  
  301.             dictionaryList=list;  
  302.         }  
  303.         return dictionaryList;  
  304.     }  
  305.       
  306.     /** 
  307.      * 有时需要强制从数据库查询最新的实际数据,所以需要刷新缓存,保证数据的实时性。 
  308.      * 这里的刷新是指把缓存中所有Element清除 
  309.      */  
  310.     public void refreshDictionaryListInMyCommonCache(){  
  311.         Cache cache=getMyCommonCache();//字典表公用缓存  
  312.         Element element=null;  
  313.         if(cache.get(MyEhcacheManager.ELEMENT_MYCOMMONCACHE_DICTIONARY)!=null){  
  314.             for(int i=0;i<cache.getKeys().size();i++){  
  315.                 cache.remove(cache.getKeys().get(i));  
  316.             }  
  317.         }  
  318.         //如果某些缓存刷新后需要马上填充,就可以像下面直接放数据  
  319. //      if(this.getMyEhcacheDao().querydictionaryByCodeNo("")!=null){  
  320. //          List list=this.getMyEhcacheDao().querydictionaryByCodeNo("");//查询  
  321. //          MyCacheObject myCacheObject = new MyCacheObject(list);  
  322. //          element=new Element((Serializable)MyEhcacheManager.ELEMENT_MYCOMMONCACHE_DICTIONARY,(Serializable)myCacheObject);  
  323. //          cache.put(element);  
  324. //          System.out.println("已经强制刷新字典表缓存。。。");  
  325. //      }  
  326.         System.out.println("已经强制清空字典表所有缓存。。。");  
  327.     }  
  328.       
  329.       
  330.       
  331.     ///  
  332.       
  333. }  


监听类MyCacheManagerEventListener

[java]  view plain copy
  1. package org.base.cache;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5. import java.util.Properties;  
  6.   
  7. import net.sf.ehcache.CacheException;  
  8. import net.sf.ehcache.CacheManager;  
  9. import net.sf.ehcache.Status;  
  10. import net.sf.ehcache.event.CacheManagerEventListener;  
  11. import net.sf.ehcache.event.CacheManagerEventListenerFactory;  
  12.   
  13.   
  14. /** 
  15.  * ehcache监听自定义 
  16.  * @author blossom
  17.  * 
  18.  */  
  19. public class MyCacheManagerEventListener  extends CacheManagerEventListenerFactory implements CacheManagerEventListener{  
  20.       
  21.     private static MyCacheManagerEventListener myCacheManagerEventListener=null;  
  22.       
  23.     public static MyCacheManagerEventListener getInstance(){  
  24.         if(myCacheManagerEventListener==null){  
  25.             myCacheManagerEventListener=new MyCacheManagerEventListener();  
  26.         }  
  27.         return myCacheManagerEventListener;  
  28.     }  
  29.   
  30.       
  31.     public void dispose() throws CacheException {  
  32.         // TODO Auto-generated method stub  
  33.         System.out.println("CacheManager was disposed.."+getTimeNow()+"(MyCacheManagerEventListener)");  
  34.     }  
  35.   
  36.     public Status getStatus() {  
  37.         // TODO Auto-generated method stub  
  38.         return null;  
  39.     }  
  40.   
  41.     public void init() throws CacheException {  
  42.         // TODO Auto-generated method stub  
  43.         System.out.println("CacheManager was inited.."+getTimeNow()+"(MyCacheManagerEventListener)");  
  44.           
  45.     }  
  46.   
  47.     public void notifyCacheAdded(String s) {  
  48.         // TODO Auto-generated method stub  
  49.         System.out.println(s+" was added.."+getTimeNow()+"(MyCacheManagerEventListener)");  
  50.     }  
  51.   
  52.     public void notifyCacheRemoved(String s) {  
  53.         // TODO Auto-generated method stub  
  54.         System.out.println(s+" was removed.."+getTimeNow()+"(MyCacheManagerEventListener)");  
  55.     }  
  56.   
  57.     @Override  
  58.     public CacheManagerEventListener createCacheManagerEventListener(  
  59.             CacheManager cachemanager, Properties properties) {  
  60.         // TODO Auto-generated method stub  
  61.         return getInstance();  
  62.     }  
  63.       
  64.     public static String getTimeNow(){  
  65.         Date dd=new Date();  
  66.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  67.         return sdf.format(dd);  
  68.     }  
  69.       
  70. }  

查询数据的公用dao

MyEhcacheDao

[java]  view plain copy
  1. package org.base.cache.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. public interface MyEhcacheDao {  
  6.       
  7.     public List querydictionaryByCodeNo(String codeNo);  
  8.   
  9. }  

MyEhcacheDaoImpl
[html]  view plain copy
  1. package org.base.cache.dao.impl;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.base.MyHibernateDao;  
  7. import org.base.cache.dao.MyEhcacheDao;  
  8.   
  9. public class MyEhcacheDaoImpl  extends MyHibernateDao implements MyEhcacheDao {  
  10.       
  11.     public List querydictionaryByCodeNo(String codeNo){  
  12.         List list=new ArrayList();  
  13.         if(codeNo==null||codeNo.trim().equals("")){  
  14.             System.out.println("参数codeNo为空,查询所有值。");  
  15.             String hql="select d from Dictionary d ";  
  16.             list=this.queryListHql(hql);  
  17.         }else{  
  18.             String hql="select d from Dictionary d where d.code_no like '"+codeNo.trim()+"%'";  
  19.             list=this.queryListHql(hql);  
  20.         }  
  21.         return list;  
  22.     }  
  23. }  

spring配置context_mycache.xml,注意除了dao的注入,还需要org.base.cache.MyEhcacheManager的注入,

org.base.cache.MyEhcacheManager在大多数情况其实相当于做了dao的代理。

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="  
  7.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  8.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd  
  9.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  
  10.   
  11.     <bean id="myEhcacheDaoTarget" class="org.base.cache.dao.impl.MyEhcacheDaoImpl">  
  12.         <property name="sessionFactory">  
  13.             <ref bean="sessionFactory"/>  
  14.         </property>  
  15.     </bean>  
  16.     <bean id="myEhcacheDao" parent="transactionProxyTemplate">  
  17.         <property name="target" ref="myEhcacheDaoTarget" />  
  18.         <property name="proxyInterfaces">  
  19.             <value>org.base.cache.dao.MyEhcacheDao</value>  
  20.         </property>  
  21.     </bean>  
  22.       
  23.     <!-- myEhcacheManager实现注入,供其他地方调用 -->  
  24.     <bean id="myEhcacheManager" class="org.base.cache.MyEhcacheManager">  
  25.         <property name="myEhcacheDao">  
  26.             <ref bean="myEhcacheDao"/>  
  27.         </property>  
  28.     </bean>  
  29. </beans>  


///以下是对公用配置表的一个查询实例

DictionaryAction

[java]  view plain copy
  1. package org.base.common.dictionary.action;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.base.MyBaseAction;  
  6. import org.base.cache.MyEhcacheManager;  
  7.   
  8. /** 
  9.  * 字典表缓存实例 
  10.  * @author blossom
  11.  * 
  12.  */  
  13. public class DictionaryAction  extends MyBaseAction {  
  14.     private static final long serialVersionUID = 1L;  
  15.     private MyEhcacheManager myEhcacheManager;  
  16.       
  17.     public String execute() throws Exception{  
  18.           
  19.         return SUCCESS;  
  20.     }  
  21.       
  22.     //查询字典表数据(注意缓存是怎么使用的)  
  23.     public String queryDictionary() throws Exception{  
  24.         String codeNo="";  
  25.         if(this.getValueFromRequest("codeNo")!=null){  
  26.             codeNo=(String)this.getValueFromRequest("codeNo");  
  27.         }  
  28.         //数据的查询通过缓存来获取  
  29.         List list=this.getMyEhcacheManager().getDictionaryListFromMyCommonCache(codeNo);  
  30.         this.setValueToRequest("dictionaryList", list);  
  31.           
  32.         return SUCCESS;  
  33.     }  
  34.       
  35.     //刷新字典表缓存  
  36.     public String refreshDictionaryInCache() throws Exception{  
  37.         this.getMyEhcacheManager().refreshDictionaryListInMyCommonCache();  
  38.         this.getPrintWriter().println("字典表缓存已刷新!");  
  39.         return NONE;  
  40.     }  
  41.   
  42.     public MyEhcacheManager getMyEhcacheManager() {  
  43.         return myEhcacheManager;  
  44.     }  
  45.   
  46.     public void setMyEhcacheManager(MyEhcacheManager myEhcacheManager) {  
  47.         this.myEhcacheManager = myEhcacheManager;  
  48.     }  
  49.       
  50. }  


struts_dictionary.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <package name="dictionary" extends="base-struts-default" namespace="/dictionary">  
  7.         <!-- 首页 -->     
  8.         <action name="queryDictionary" class="org.base.common.dictionary.action.DictionaryAction" method="queryDictionary">  
  9.            <result name="success">/jsp/dictionary/dictionary_list.jsp</result>  
  10.         </action>  
  11.         <action name="refreshDictionaryInCache" class="org.base.common.dictionary.action.DictionaryAction" method="refreshDictionaryInCache">  
  12.         </action>  
  13.     </package>  
  14. </struts>  

dictionary_list.jsp
[html]  view plain copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags"%>  
  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  4. <%@ page import="java.util.*"%>  
  5. <%@page import="java.text.*"%>  
  6. <%@ page import="org.base.common.dictionary.bean.Dictionary"%>  
  7. <%   
  8. String path = request.getContextPath();  
  9. %>  
  10. <%   
  11. List list=null;  
  12. if(request.getAttribute("dictionaryList")!=null){  
  13.     list=(List)request.getAttribute("dictionaryList");  
  14. }  
  15. %>  
  16. <html>  
  17.     <head>  
  18.         <meta name="author" content="lushuaiyin">  
  19.         <meta name="description" content="http://blog.csdn.net/lushuaiyin">  
  20.         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  21.         <title>uploadFile</title>  
  22.         <link rel="stylesheet" type="text/css" href="<%=path%>/resource/css/table.css" />  
  23.         <script src="<%=path%>/script/jquery-1.7.1.min.js" type="text/javascript"></script>     
  24.     </head>  
  25.     <body>  
  26.     <input type="hidden" value="<%=path%>" id="path">  
  27.       
  28.       
  29.   
  30.     <table  align="center" width="80%" class="table2">  
  31.               <tr>  
  32.                 <td><input type="text" value="" id="codeNo"/></td>  
  33.               </tr>     
  34.                <tr>  
  35.                 <td><input type="button" value="查询" onclick="chaxun()"/></td>  
  36.                 <td><input type="button" value="刷新缓存" onclick="refreshcache()"/></td>  
  37.               </tr>     
  38.         </table>  
  39.         <table id="mytable1" align="center" width="80%" class="table1">  
  40.               <tr>  
  41.                 <th>code_no</th>  
  42.                 <th>code_name</th>  
  43.                 <th>create_time</th>  
  44.                 <th>create_user</th>  
  45.               </tr>  
  46.               <%   
  47.               if(list!=null){  
  48.                   
  49.                   for(int i=0;i<list.size();i++){  
  50.                       Dictionary vo=(Dictionary)list.get(i);  
  51.                       String code_no="",code_name="",create_time="",create_user="";  
  52.                       code_no=vo.getCode_no()==null?"":vo.getCode_no().trim();  
  53.                       code_name=vo.getCode_name()==null?"":vo.getCode_name().trim();  
  54.                         
  55.                       Date date=vo.getCreate_time();  
  56.                       SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  57.                       create_time=sdf.format(date);  
  58.                         
  59.                       create_user=vo.getCreate_user()==null?"":vo.getCreate_user().trim();  
  60.                      if(i%2==0){  
  61.                          %>  
  62.               <tr class="interval">  
  63.                <td><%=code_no%></td>  
  64.                 <td><%=code_name%></td>  
  65.                 <td><%=create_time%></td>  
  66.                 <td><%=create_user%></td>  
  67.               </tr>  
  68.                            
  69.                          <%   
  70.                      }else{  
  71.                          %>  
  72.                <tr>  
  73.                 <td><%=code_no%></td>  
  74.                 <td><%=code_name%></td>  
  75.                 <td><%=create_time%></td>  
  76.                 <td><%=create_user%></td>  
  77.               </tr>          
  78.                          <%  
  79.                      }   
  80.                   }  
  81.               }  
  82.               %>  
  83.         </table>  
  84.     </body>  
  85. </html>  
  86.   
  87. <script type="text/javascript">  
  88. var path=document.getElementById("path").value;  
  89.   
  90.   
  91. function chaxun(){  
  92.     var codeNo=document.getElementById("codeNo").value;  
  93.     var url=path+"/dictionary/queryDictionary.action?codeNo="+codeNo;  
  94.     window.location.href=url;  
  95. }  
  96.   
  97. function refreshcache(){  
  98.     var url=path+"/dictionary/refreshDictionaryInCache.action";  
  99.     $.ajax({  
  100.            type: "POST",  
  101.            url: url,  
  102.            success: callbackrefreshcache  
  103.         });  
  104. }  
  105. function callbackrefreshcache(data){  
  106.     alert(data);  
  107.     window.location.reload();  
  108. }  
  109. </script>  


///测试打印


2013-5-1 15:26:29 org.apache.catalina.core.AprLifecycleListener init
信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.6.0_06\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files\Java\jdk1.6.0_06\jre\bin;C:/Program Files/Java/jre1.6.0_06/bin/client;C:/Program Files/Java/jre1.6.0_06/bin;C:/Program Files/Java/jre1.6.0_06/lib/i386;D:\app\lushuaiyin\product\11.2.0\client_1\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.6.0_06\bin;C:\Program Files\TortoiseSVN\bin;D:\MySql\bin;C:\Program Files\QuickTime\QTSystem\;C:\Windows\System32;C:\Program Files\VanDyke Software\Clients\;D:\ChinaDevelopmentBankAct\eclipse;
2013-5-1 15:26:30 org.apache.coyote.http11.Http11Protocol init
信息: Initializing Coyote HTTP/1.1 on http-8080
2013-5-1 15:26:30 org.apache.catalina.startup.Catalina load
信息: Initialization processed in 674 ms
2013-5-1 15:26:30 org.apache.catalina.core.StandardService start
信息: Starting service Catalina
2013-5-1 15:26:30 org.apache.catalina.core.StandardEngine start
信息: Starting Servlet Engine: Apache Tomcat/6.0.35
2013-5-1 15:26:30 org.apache.catalina.startup.HostConfig deployDescriptor
信息: Deploying configuration descriptor frame.xml
2013-5-1 15:26:30 org.apache.catalina.loader.WebappClassLoader validateJarFile
信息: validateJarFile(D:\ChinaDevelopmentBankAct\workSpace\frame\webapp\WEB-INF\lib\servlet-api-2.5.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
2013-5-1 15:26:31 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring root WebApplicationContext
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
CacheManager was inited..2013-05-01 15:26:34(MyCacheManagerEventListener)
myCommonCache was added..2013-05-01 15:26:35(MyCacheManagerEventListener)
2013-5-1 15:26:39 org.activiti.engine.impl.ProcessEngineImpl <init>
信息: ProcessEngine default created
 TestServlet init---
2013-5-1 15:26:42 org.apache.catalina.startup.HostConfig deployDescriptor
信息: Deploying configuration descriptor host-manager.xml
2013-5-1 15:26:42 org.apache.catalina.startup.HostConfig deployDescriptor
信息: Deploying configuration descriptor manager.xml
2013-5-1 15:26:42 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deploying web application directory docs
2013-5-1 15:26:42 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deploying web application directory examples
2013-5-1 15:26:42 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextInitialized()
2013-5-1 15:26:42 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextInitialized()
2013-5-1 15:26:42 org.apache.coyote.http11.Http11Protocol start
信息: Starting Coyote HTTP/1.1 on http-8080
2013-5-1 15:26:42 org.apache.jk.common.ChannelSocket init
信息: JK: ajp13 listening on /0.0.0.0:8009
2013-5-1 15:26:42 org.apache.jk.server.JkMain start
信息: Jk running ID=0 time=0/44  config=null
2013-5-1 15:26:42 org.apache.catalina.startup.Catalina start
信息: Server startup in 12418 ms
参数codeNo为空,查询所有值。
Hibernate: select dictionary0_.id as id3_, dictionary0_.code_no as code2_3_, dictionary0_.code_name as code3_3_, dictionary0_.code_parent_no as code4_3_, dictionary0_.show_order as show5_3_, dictionary0_.create_time as create6_3_, dictionary0_.remark as remark3_, dictionary0_.create_user as create8_3_, dictionary0_.valid as valid3_, dictionary0_.bak1 as bak10_3_, dictionary0_.bak2 as bak11_3_, dictionary0_.bak3 as bak12_3_ from LSY_DICTIONARY dictionary0_
缓存中的字典表元素为空,重新查询添加......
缓存中存在字典表数据,直接获取到。
参数codeNo为空,查询所有值。
Hibernate: select dictionary0_.id as id3_, dictionary0_.code_no as code2_3_, dictionary0_.code_name as code3_3_, dictionary0_.code_parent_no as code4_3_, dictionary0_.show_order as show5_3_, dictionary0_.create_time as create6_3_, dictionary0_.remark as remark3_, dictionary0_.create_user as create8_3_, dictionary0_.valid as valid3_, dictionary0_.bak1 as bak10_3_, dictionary0_.bak2 as bak11_3_, dictionary0_.bak3 as bak12_3_ from LSY_DICTIONARY dictionary0_
缓存中的字典表元素为空,重新查询添加......
已经强制清空字典表所有缓存。。。
参数codeNo为空,查询所有值。
Hibernate: select dictionary0_.id as id3_, dictionary0_.code_no as code2_3_, dictionary0_.code_name as code3_3_, dictionary0_.code_parent_no as code4_3_, dictionary0_.show_order as show5_3_, dictionary0_.create_time as create6_3_, dictionary0_.remark as remark3_, dictionary0_.create_user as create8_3_, dictionary0_.valid as valid3_, dictionary0_.bak1 as bak10_3_, dictionary0_.bak2 as bak11_3_, dictionary0_.bak3 as bak12_3_ from LSY_DICTIONARY dictionary0_
缓存中的字典表元素为空,重新查询添加......

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值