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

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

 

缓存主要可分为二大类:

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

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

代码如下 :
  1. package lhm.hcy.guge.frameset.cache; 

  2. import java.util.*; 

  3. //Description: 管理缓存 

  4. //可扩展的功能:当chche到内存溢出时必须清除掉最早期的一些缓存对象,这就要求对每个缓存对象保存创建时间 

  5. public class CacheManager { 
  6.     private static HashMap cacheMap = new HashMap(); 

  7.     //单实例构造方法 
  8.     private CacheManager() { 
  9.         super(); 
  10.     } 
  11.     //获取布尔值的缓存 
  12.     public static boolean getSimpleFlag(String key){ 
  13.         try{ 
  14.             return (Boolean) cacheMap.get(key); 
  15.         }catch(NullPointerException e){ 
  16.             return false; 
  17.         } 
  18.     } 
  19.     public static long getServerStartdt(String key){ 
  20.         try { 
  21.             return (Long)cacheMap.get(key); 
  22.         } catch (Exception ex) { 
  23.             return 0; 
  24.         } 
  25.     } 
  26.     //设置布尔值的缓存 
  27.     public synchronized static boolean setSimpleFlag(String key,boolean flag){ 
  28.         if (flag && getSimpleFlag(key)) {//假如为真不允许被覆盖 
  29.             return false; 
  30.         }else{ 
  31.             cacheMap.put(key, flag); 
  32.             return true; 
  33.         } 
  34.     } 
  35.     public synchronized static boolean setSimpleFlag(String key,long serverbegrundt){ 
  36.         if (cacheMap.get(key) == null) { 
  37.             cacheMap.put(key,serverbegrundt); 
  38.             return true; 
  39.         }else{ 
  40.             return false; 
  41.         } 
  42.     } 

  43.     //得到缓存。同步静态方法 
  44.     private synchronized static Cache getCache(String key) { 
  45.         return (Cache) cacheMap.get(key); 
  46.     } 

  47.     //判断是否存在一个缓存 
  48.     private synchronized static boolean hasCache(String key) { 
  49.         return cacheMap.containsKey(key); 
  50.     } 

  51.     //清除所有缓存 
  52.     public synchronized static void clearAll() { 
  53.         cacheMap.clear(); 
  54.     } 

  55.     //清除某一类特定缓存,通过遍历HASHMAP下的所有对象,来判断它的KEY与传入的TYPE是否匹配 
  56.     public synchronized static void clearAll(String type) { 
  57.         Iterator i = cacheMap.entrySet().iterator(); 
  58.         String key; 
  59.         ArrayList arr = new ArrayList(); 
  60.         try { 
  61.             while (i.hasNext()) { 
  62.                 java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
  63.                 key = (String) entry.getKey(); 
  64.                 if (key.startsWith(type)) { //如果匹配则删除掉 
  65.                     arr.add(key); 
  66.                 } 
  67.             } 
  68.             for (int k = 0; k < arr.size(); k++) { 
  69.                 clearOnly(arr.get(k)); 
  70.             } 
  71.         } catch (Exception ex) { 
  72.             ex.printStackTrace(); 
  73.         } 
  74.     } 

  75.     //清除指定的缓存 
  76.     public synchronized static void clearOnly(String key) { 
  77.         cacheMap.remove(key); 
  78.     } 

  79.     //载入缓存 
  80.     public synchronized static void putCache(String key, Cache obj) { 
  81.         cacheMap.put(key, obj); 
  82.     } 

  83.     //获取缓存信息 
  84.     public static Cache getCacheInfo(String key) { 

  85.         if (hasCache(key)) { 
  86.             Cache cache = getCache(key); 
  87.             if (cacheExpired(cache)) { //调用判断是否终止方法 
  88.                 cache.setExpired(true); 
  89.             } 
  90.             return cache; 
  91.         }else 
  92.             return null; 
  93.     } 

  94.     //载入缓存信息 
  95.     public static void putCacheInfo(String key, Cache obj, long dt,boolean expired) { 
  96.         Cache cache = new Cache(); 
  97.         cache.setKey(key); 
  98.         cache.setTimeOut(dt + System.currentTimeMillis()); //设置多久后更新缓存 
  99.         cache.setValue(obj); 
  100.         cache.setExpired(expired); //缓存默认载入时,终止状态为FALSE 
  101.         cacheMap.put(key, cache); 
  102.     } 
  103.     //重写载入缓存信息方法 
  104.     public static void putCacheInfo(String key,Cache obj,long dt){ 
  105.         Cache cache = new Cache(); 
  106.         cache.setKey(key); 
  107.         cache.setTimeOut(dt+System.currentTimeMillis()); 
  108.         cache.setValue(obj); 
  109.         cache.setExpired(false); 
  110.         cacheMap.put(key,cache); 
  111.     } 

  112.     //判断缓存是否终止 
  113.     public static boolean cacheExpired(Cache cache) { 
  114.         if (null == cache) { //传入的缓存不存在 
  115.             return false; 
  116.         } 
  117.         long nowDt = System.currentTimeMillis(); //系统当前的毫秒数 
  118.         long cacheDt = cache.getTimeOut(); //缓存内的过期毫秒数 
  119.         if (cacheDt <= 0||cacheDt>nowDt) { //过期时间小于等于零时,或者过期时间大于当前时间时,则为FALSE 
  120.             return false; 
  121.         } else { //大于过期时间 即过期 
  122.             return true; 
  123.         } 
  124.     } 

  125.     //获取缓存中的大小 
  126.     public static int getCacheSize() { 
  127.         return cacheMap.size(); 
  128.     } 

  129.     //获取指定的类型的大小 
  130.     public static int getCacheSize(String type) { 
  131.         int k = 0; 
  132.         Iterator i = cacheMap.entrySet().iterator(); 
  133.         String key; 
  134.         try { 
  135.             while (i.hasNext()) { 
  136.                 java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
  137.                 key = (String) entry.getKey(); 
  138.                 if (key.indexOf(type) != -1) { //如果匹配则删除掉 
  139.                     k++; 
  140.                 } 
  141.             } 
  142.         } catch (Exception ex) { 
  143.             ex.printStackTrace(); 
  144.         } 

  145.         return k; 
  146.     } 

  147.     //获取缓存对象中的所有键值名称 
  148.     public static ArrayList getCacheAllkey() { 
  149.         ArrayList a = new ArrayList(); 
  150.         try { 
  151.             Iterator i = cacheMap.entrySet().iterator(); 
  152.             while (i.hasNext()) { 
  153.                 java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
  154.                 a.add((String) entry.getKey()); 
  155.             } 
  156.         } catch (Exception ex) {} finally { 
  157.             return a; 
  158.         } 
  159.     } 

  160.     //获取缓存对象中指定类型 的键值名称 
  161.     public static ArrayList getCacheListkey(String type) { 
  162.         ArrayList a = new ArrayList(); 
  163.         String key; 
  164.         try { 
  165.             Iterator i = cacheMap.entrySet().iterator(); 
  166.             while (i.hasNext()) { 
  167.                 java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
  168.                 key = (String) entry.getKey(); 
  169.                 if (key.indexOf(type) != -1) { 
  170.                     a.add(key); 
  171.                 } 
  172.             } 
  173.         } catch (Exception ex) {} finally { 
  174.             return a; 
  175.         } 
  176.     } 



  177. package lhm.hcy.guge.frameset.cache; 

  178. public class Cache { 
  179.         private String key;//缓存ID 
  180.         private Object value;//缓存数据 
  181.         private long timeOut;//更新时间 
  182.         private boolean expired; //是否终止 
  183.         public Cache() { 
  184.                 super(); 
  185.         } 

  186.         public Cache(String key, Object value, long timeOut, boolean expired) { 
  187.                 this.key = key; 
  188.                 this.value = value; 
  189.                 this.timeOut = timeOut; 
  190.                 this.expired = expired; 
  191.         } 

  192.         public String getKey() { 
  193.                 return key; 
  194.         } 

  195.         public long getTimeOut() { 
  196.                 return timeOut; 
  197.         } 

  198.         public Object getValue() { 
  199.                 return value; 
  200.         } 

  201.         public void setKey(String string) { 
  202.                 key = string; 
  203.         } 

  204.         public void setTimeOut(long l) { 
  205.                 timeOut = l; 
  206.         } 

  207.         public void setValue(Object object) { 
  208.                 value = object; 
  209.         } 

  210.         public boolean isExpired() { 
  211.                 return expired; 
  212.         } 

  213.         public void setExpired(boolean b) { 
  214.                 expired = b; 
  215.         } 


  216. //测试类, 
  217. class Test { 
  218.     public static void main(String[] args) { 
  219.         System.out.println(CacheManager.getSimpleFlag("alksd")); 
  220. //        CacheManager.putCache("abc", new Cache()); 
  221. //        CacheManager.putCache("def", new Cache()); 
  222. //        CacheManager.putCache("ccc", new Cache()); 
  223. //        CacheManager.clearOnly(""); 
  224. //        Cache c = new Cache(); 
  225. //        for (int i = 0; i < 10; i++) { 
  226. //            CacheManager.putCache("" + i, c); 
  227. //        } 
  228. //        CacheManager.putCache("aaaaaaaa", c); 
  229. //        CacheManager.putCache("abchcy;alskd", c); 
  230. //        CacheManager.putCache("cccccccc", c); 
  231. //        CacheManager.putCache("abcoqiwhcy", c); 
  232. //        System.out.println("删除前的大小:"+CacheManager.getCacheSize()); 
  233. //        CacheManager.getCacheAllkey(); 
  234. //        CacheManager.clearAll("aaaa"); 
  235. //        System.out.println("删除后的大小:"+CacheManager.getCacheSize()); 
  236. //        CacheManager.getCacheAllkey(); 

  237.     } 
  238. }
复制代码

本文由:http://www.mfqyw.com/ 编辑整理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值