分享

Java 中常用缓存Cache机制的实现

 instl 2014-11-04

cache

Cache

所谓缓存,就是将程序或系统经常要调用的对象存在内存中,一遍其使用时可以快速调用,不必再去创建新的重复的实例。这样做可以减少系统开销,提高系统效率。

缓存主要可分为二大类: 

一、通过文件缓存,顾名思义文件缓存是指把数据存储在磁盘上,不管你是以XML格式,序列化文件DAT格式还是其它文件格式;  

二、内存缓存,也就是实现一个类中静态Map,对这个Map进行常规的增删查. 

代码如下 :

  1. package lhm.hcy.guge.frameset.cache; 
  2.  
  3. import java.util.*; 
  4.  
  5.  //Description: 管理缓存 
  6.  
  7.  //可扩展的功能:当chche到内存溢出时必须清除掉最早期的一些缓存对象,这就要求对每个缓存对象保存创建时间 
  8.  
  9. public class CacheManager { 
  10.     private static HashMap cacheMap = new HashMap(); 
  11.  
  12.     //单实例构造方法 
  13.     private CacheManager() { 
  14.         super(); 
  15.     } 
  16.     //获取布尔值的缓存 
  17.     public static boolean getSimpleFlag(String key){ 
  18.         try{ 
  19.             return (Boolean) cacheMap.get(key); 
  20.         }catch(NullPointerException e){ 
  21.             return false; 
  22.         } 
  23.     } 
  24.     public static long getServerStartdt(String key){ 
  25.         try { 
  26.             return (Long)cacheMap.get(key); 
  27.         } catch (Exception ex) { 
  28.             return 0; 
  29.         } 
  30.     } 
  31.     //设置布尔值的缓存 
  32.     public synchronized static boolean setSimpleFlag(String key,boolean flag){ 
  33.         if (flag && getSimpleFlag(key)) {//假如为真不允许被覆盖 
  34.             return false; 
  35.         }else{ 
  36.             cacheMap.put(key, flag); 
  37.             return true; 
  38.         } 
  39.     } 
  40.     public synchronized static boolean setSimpleFlag(String key,long serverbegrundt){ 
  41.         if (cacheMap.get(key) == null) { 
  42.             cacheMap.put(key,serverbegrundt); 
  43.             return true; 
  44.         }else{ 
  45.             return false; 
  46.         } 
  47.     } 
  48.  
  49.  
  50.     //得到缓存。同步静态方法 
  51.     private synchronized static Cache getCache(String key) { 
  52.         return (Cache) cacheMap.get(key); 
  53.     } 
  54.  
  55.     //判断是否存在一个缓存 
  56.     private synchronized static boolean hasCache(String key) { 
  57.         return cacheMap.containsKey(key); 
  58.     } 
  59.  
  60.     //清除所有缓存 
  61.     public synchronized static void clearAll() { 
  62.         cacheMap.clear(); 
  63.     } 
  64.  
  65.     //清除某一类特定缓存,通过遍历HASHMAP下的所有对象,来判断它的KEY与传入的TYPE是否匹配 
  66.     public synchronized static void clearAll(String type) { 
  67.         Iterator i = cacheMap.entrySet().iterator(); 
  68.         String key; 
  69.         ArrayList arr = new ArrayList(); 
  70.         try { 
  71.             while (i.hasNext()) { 
  72.                 java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
  73.                 key = (String) entry.getKey(); 
  74.                 if (key.startsWith(type)) { //如果匹配则删除掉 
  75.                     arr.add(key); 
  76.                 } 
  77.             } 
  78.             for (int k = 0; k < arr.size(); k++) { 
  79.                 clearOnly(arr.get(k)); 
  80.             } 
  81.         } catch (Exception ex) { 
  82.             ex.printStackTrace(); 
  83.         } 
  84.     } 
  85.  
  86.     //清除指定的缓存 
  87.     public synchronized static void clearOnly(String key) { 
  88.         cacheMap.remove(key); 
  89.     } 
  90.  
  91.     //载入缓存 
  92.     public synchronized static void putCache(String key, Cache obj) { 
  93.         cacheMap.put(key, obj); 
  94.     } 
  95.  
  96.     //获取缓存信息 
  97.     public static Cache getCacheInfo(String key) { 
  98.  
  99.         if (hasCache(key)) { 
  100.             Cache cache = getCache(key); 
  101.             if (cacheExpired(cache)) { //调用判断是否终止方法 
  102.                 cache.setExpired(true); 
  103.             } 
  104.             return cache; 
  105.         }else 
  106.             return null; 
  107.     } 
  108.  
  109.     //载入缓存信息 
  110.     public static void putCacheInfo(String key, Cache obj, long dt,boolean expired) { 
  111.         Cache cache = new Cache(); 
  112.         cache.setKey(key); 
  113.         cache.setTimeOut(dt + System.currentTimeMillis()); //设置多久后更新缓存 
  114.         cache.setValue(obj); 
  115.         cache.setExpired(expired); //缓存默认载入时,终止状态为FALSE 
  116.         cacheMap.put(key, cache); 
  117.     } 
  118.     //重写载入缓存信息方法 
  119.     public static void putCacheInfo(String key,Cache obj,long dt){ 
  120.         Cache cache = new Cache(); 
  121.         cache.setKey(key); 
  122.         cache.setTimeOut(dt+System.currentTimeMillis()); 
  123.         cache.setValue(obj); 
  124.         cache.setExpired(false); 
  125.         cacheMap.put(key,cache); 
  126.     } 
  127.  
  128.     //判断缓存是否终止 
  129.     public static boolean cacheExpired(Cache cache) { 
  130.         if (null == cache) { //传入的缓存不存在 
  131.             return false; 
  132.         } 
  133.         long nowDt = System.currentTimeMillis(); //系统当前的毫秒数 
  134.         long cacheDt = cache.getTimeOut(); //缓存内的过期毫秒数 
  135.         if (cacheDt <= 0||cacheDt>nowDt) { //过期时间小于等于零时,或者过期时间大于当前时间时,则为FALSE 
  136.             return false; 
  137.         } else { //大于过期时间 即过期 
  138.             return true; 
  139.         } 
  140.     } 
  141.  
  142.     //获取缓存中的大小 
  143.     public static int getCacheSize() { 
  144.         return cacheMap.size(); 
  145.     } 
  146.  
  147.     //获取指定的类型的大小 
  148.     public static int getCacheSize(String type) { 
  149.         int k = 0; 
  150.         Iterator i = cacheMap.entrySet().iterator(); 
  151.         String key; 
  152.         try { 
  153.             while (i.hasNext()) { 
  154.                 java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
  155.                 key = (String) entry.getKey(); 
  156.                 if (key.indexOf(type) != -1) { //如果匹配则删除掉 
  157.                     k++; 
  158.                 } 
  159.             } 
  160.         } catch (Exception ex) { 
  161.             ex.printStackTrace(); 
  162.         } 
  163.  
  164.         return k; 
  165.     } 
  166.  
  167.     //获取缓存对象中的所有键值名称 
  168.     public static ArrayList getCacheAllkey() { 
  169.         ArrayList a = new ArrayList(); 
  170.         try { 
  171.             Iterator i = cacheMap.entrySet().iterator(); 
  172.             while (i.hasNext()) { 
  173.                 java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
  174.                 a.add((String) entry.getKey()); 
  175.             } 
  176.         } catch (Exception ex) {} finally { 
  177.             return a; 
  178.         } 
  179.     } 
  180.  
  181.     //获取缓存对象中指定类型 的键值名称 
  182.     public static ArrayList getCacheListkey(String type) { 
  183.         ArrayList a = new ArrayList(); 
  184.         String key; 
  185.         try { 
  186.             Iterator i = cacheMap.entrySet().iterator(); 
  187.             while (i.hasNext()) { 
  188.                 java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
  189.                 key = (String) entry.getKey(); 
  190.                 if (key.indexOf(type) != -1) { 
  191.                     a.add(key); 
  192.                 } 
  193.             } 
  194.         } catch (Exception ex) {} finally { 
  195.             return a; 
  196.         } 
  197.     } 
  198.  
  199.  
  200.  
  201. package lhm.hcy.guge.frameset.cache; 
  202.  
  203. public class Cache { 
  204.         private String key;//缓存ID 
  205.         private Object value;//缓存数据 
  206.         private long timeOut;//更新时间 
  207.         private boolean expired; //是否终止 
  208.         public Cache() { 
  209.                 super(); 
  210.         } 
  211.  
  212.         public Cache(String key, Object value, long timeOut, boolean expired) { 
  213.                 this.key = key; 
  214.                 this.value = value; 
  215.                 this.timeOut = timeOut; 
  216.                 this.expired = expired; 
  217.         } 
  218.  
  219.         public String getKey() { 
  220.                 return key; 
  221.         } 
  222.  
  223.         public long getTimeOut() { 
  224.                 return timeOut; 
  225.         } 
  226.  
  227.         public Object getValue() { 
  228.                 return value; 
  229.         } 
  230.  
  231.         public void setKey(String string) { 
  232.                 key = string; 
  233.         } 
  234.  
  235.         public void setTimeOut(long l) { 
  236.                 timeOut = l; 
  237.         } 
  238.  
  239.         public void setValue(Object object) { 
  240.                 value = object; 
  241.         } 
  242.  
  243.         public boolean isExpired() { 
  244.                 return expired; 
  245.         } 
  246.  
  247.         public void setExpired(boolean b) { 
  248.                 expired = b; 
  249.         } 
  250.  
  251. //测试类, 
  252. class Test { 
  253.     public static void main(String[] args) { 
  254.         System.out.println(CacheManager.getSimpleFlag("alksd")); 
  255. //        CacheManager.putCache("abc", new Cache()); 
  256. //        CacheManager.putCache("def", new Cache()); 
  257. //        CacheManager.putCache("ccc", new Cache()); 
  258. //        CacheManager.clearOnly(""); 
  259. //        Cache c = new Cache(); 
  260. //        for (int i = 0; i < 10; i++) { 
  261. //            CacheManager.putCache("" + i, c); 
  262. //        } 
  263. //        CacheManager.putCache("aaaaaaaa", c); 
  264. //        CacheManager.putCache("abchcy;alskd", c); 
  265. //        CacheManager.putCache("cccccccc", c); 
  266. //        CacheManager.putCache("abcoqiwhcy", c); 
  267. //        System.out.println("删除前的大小:"+CacheManager.getCacheSize()); 
  268. //        CacheManager.getCacheAllkey(); 
  269. //        CacheManager.clearAll("aaaa"); 
  270. //        System.out.println("删除后的大小:"+CacheManager.getCacheSize()); 
  271. //        CacheManager.getCacheAllkey(); 
  272.  
  273.  
  274.     } 

 

【编辑推荐】

【责任编辑:张伟 TEL:(010)68476606】

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

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多