1 packagecom.wbproject.util.cache;2
3 importjava.time.LocalDateTime;4 importjava.time.format.DateTimeFormatter;5 importjava.util.Date;6 importjava.util.HashMap;7 importjava.util.HashSet;8 importjava.util.Iterator;9 importjava.util.Map;10 importjava.util.Set;11
12 /**
13 * 缓存管理类14 *15 *@authorwangbo16 * @date 2018-03-07 12:43:4117 */
18 public classCacheManage {19
20 private static Map cacheMap = new HashMap<>();21
22 private static Map cacheConfMap = new HashMap<>();23
24 private static CacheManage cm = null;25
26 //构造方法私有化
27 privateCacheManage() {28 }29
30 //获取实例
31 public staticCacheManage getInstance() {32 if (cm == null) {33 cm = newCacheManage();34 //第一次获取实例的时候启动线程
35 Thread t = newClearCache();36 t.start();37 }38 returncm;39 }40
41 /**
42 * 添加缓存实体43 *44 *@paramkey45 *@paramvalue46 *@paramccm47 *@return
48 */
49 public booleanaddCache(Object key, Object value, CacheConfModel ccm) {50 System.out.println("开始增加缓存");51 boolean flag = false;52 try{53 cacheMap.put(key, value);54 cacheConfMap.put(key, ccm);55 System.out.println("增加缓存结束");56 flag = true;57 } catch(Exception e) {58 e.printStackTrace();59 }60
61 returnflag;62 }63
64 /**
65 * 获取缓存实体66 *67 *@paramkey68 *@return
69 */
70 publicObject getValue(Object key) {71 Object object =cacheMap.get(key);72 if (object != null) {73 returnobject;74 } else{75 return null;76 }77 }78
79 /**
80 * 获取缓存数据的数量81 *82 *@return
83 */
84 public intgetSize() {85 returncacheMap.size();86 }87
88 /**
89 * 删除缓存90 *91 *@paramkey92 *@return
93 */
94 public booleanremoveCache(Object key) {95 boolean flag = false;96 try{97 cacheMap.remove(key);98 cacheConfMap.remove(key);99 flag = true;100 } catch(Exception e) {101 e.printStackTrace();102 }103 returnflag;104 }105
106 /**
107 * 清除缓存的线程108 */
109 private static class ClearCache extendsThread {110 public voidrun() {111 while (true) {112 //记录要清除的key
113 Set tempSet = new HashSet<>();114 Set set =cacheConfMap.keySet();115 Iterator it =set.iterator();116 while(it.hasNext()) {117 Object key =it.next();118 CacheConfModel ccm =(CacheConfModel) cacheConfMap.get(key);119 //比较是否需要清除
120 if (!ccm.isForever()) {121 if ((new Date().getTime() - ccm.getBeginTime()) >= ccm.getDurableTime() * 1000L) {122 //可以清除,先记录下来
123 tempSet.add(key);124 }125 }126 }127 //真正清除
128 Iterator tempIt =tempSet.iterator();129 while(tempIt.hasNext()) {130 Object key =tempIt.next();131 cacheMap.remove(key);132 cacheConfMap.remove(key);133 }134
135 LocalDateTime localDateTime =LocalDateTime.now();136 System.out.println("当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + ",缓存大小==>" +cacheMap.size());137 //线程休息
138 try{139 Thread.sleep(60 * 10 * 1000L);140 } catch(InterruptedException e) {141 e.printStackTrace();142 }143 }144 }145 }146
147 }