今天做需求发现得使用缓存,但是这个项目里面没引入redis等,又不想麻烦引入所以就使用map作为缓存使用,便记录下来,也许对大家有需要。
首先定义一些所需要的变量等作为Map的key:
//用于缓冲数据Map private HashMap<String, Object> cacheMap = new HashMap<String, Object>(); //时间key private final static String TIME_KEY = "cateTime"; //数据key private final static String DATE_KEY = "cateList"; //缓冲时间1天 private final static long EXPIRATIONTIME = 1000 * 60 * 60 * 24;
下面是cotroller返回的数据,判断有无缓存,有就走缓存没有就走数据代码很清晰
/** * 需要查询的List数据 * 返回true:走缓存 * 返回false:走数据库 */ @RequestMapping("queryList") public JsonView queryList() { //调用isInvalid方法,传入时间key,数据key if(isInvalid(TIME_KEY,DATE_KEY)){ return new JsonView(cacheMap.get(DATE_KEY)); } List<ProductBrandEntity> list = productBrandService.queryList(); //将查出来的数据放入map cacheMap.put(DATE_KEY, list); //设置缓存时间 cacheMap.put(TIME_KEY, System.currentTimeMillis() + EXPIRATIONTIME); return new JsonView(list); }
这方法是用来判断缓存失效时间的,过期清除缓存
/* * 是否过期 */ private boolean isInvalid(String timeKey,String dataKey){ //如果时间key为null或者map里没这个key就查数据库 if (timeKey == null || !cacheMap.containsKey(timeKey)) return false; Long expiryTime = (Long)cacheMap.get(timeKey); //如果当前时间大于缓存过期时间就移除map里的数据key if(System.currentTimeMillis() > expiryTime.longValue()){ cacheMap.remove(dataKey); return false; } return true; }