用HashMap封装一个内置缓存:
开楼吧:
首先搭个框架:
SpringBoot+Mybatis
然后编写内置缓存:
public class JvmMapCacheUtils { private static Mapcaches = new ConcurrentHashMap<>(); public static List listEntity(String key, Class t){ //return JSONObject.parseObject(caches.get(key),t); return JSONObject.parseArray(caches.get(key),t); } public static void put(String key,Object o){ caches.put(key,JSONObject.toJSonString(o)); } public static T getEntity(String key, Class t){ return JSONObject.parseObject(caches.get(key),t); } }
我们来测试下:
@PostMapping("/listUser") public ResponseMessage listUser(HttpServletRequest request){ ResponseMessage responseMessage = new ResponseMessage(0); try{ String token = request.getHeader("token"); logger.info("token的值:【{}】"+token); Listuser = null; user = JvmMapCacheUtils.listEntity(token, User.class); //如果等于空 if(StringUtils.isEmpty(user)){ //模拟耗时时间 Thread.sleep(1000); JvmMapCacheUtils.put(token,userService.getUser()); responseMessage.setMessage(userService.getUser()); }else { responseMessage.setMessage(user); } }catch (Exception ex){ logger.error("查询用户信息信息异常", ex); throw new RuntimeException(ex.getMessage()); } return responseMessage; }
走数据库耗时1270毫秒多
走缓存,耗时9毫秒
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)