mongodb 实现数据缓存
mongodb缓存结果
private MongoOperations mongoTemplate; public Object methodCacheHold(ProceedingJoinPoint joinPoint) throws Throwable { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); // Class<?> returnType = joinPoint.getClass().getMethod(methodName).getReturnType(); String cacheKey = getCacheKey(targetName, methodName, arguments); CacheEntity cacheEntity = mongoTemplate.findById(cacheKey, CacheEntity.class); Object result = null; if (cacheEntity == null) { result = joinPoint.proceed(); // if (result != null) { cacheEntity = new CacheEntity(); cacheEntity.setId(cacheKey);//key为类名,方法名和参数组成字符串 cacheEntity.setEntity(result); mongoTemplate.insert(cacheEntity); // } } else { result = cacheEntity.getEntity(); } return result; } private String getCacheKey(String targetName, String methodName, Object[] arguments) { StringBuffer sb = new StringBuffer(); sb.append(targetName).append(".").append(methodName); if ((arguments != null) && (arguments.length != 0)) { for (int i = 0; i < arguments.length; i++) { if (arguments[i] instanceof Date) { sb.append(".").append(((Date) arguments[i]).getTime()); } else { sb.append(".").append(arguments[i]); } } } return sb.toString(); }
清楚mongodb缓存结果
private MongoOperations mongoTemplate; public Object removeCacheHold(ProceedingJoinPoint joinPoint) throws Throwable { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); // Class<?> returnType = joinPoint.getClass().getMethod(methodName).getReturnType(); String cacheKey = getCacheKey(targetName, methodName, arguments); CacheEntity cacheEntity = new CacheEntity(); cacheEntity.setId(cacheKey); mongoTemplate.remove(cacheEntity); Object result = null; result = joinPoint.proceed(); return result; } private String getCacheKey(String targetName, String methodName, Object[] arguments) { StringBuffer sb = new StringBuffer(); methodName = methodName.replace("CacheRemove", "Cache");//清楚的方法名规则为添加缓存的方法名后加上Remove sb.append(targetName).append(".").append(methodName); if ((arguments != null) && (arguments.length != 0)) { for (int i = 0; i < arguments.length; i++) { if (arguments[i] instanceof Date) { sb.append(".").append(((Date) arguments[i]).getTime()); } else { sb.append(".").append(arguments[i]); } } } return sb.toString(); }
通过添加在方法上的annotation触发执行缓存的保存和更新
相关推荐
大秦铁骑 2020-08-19
thatway 2020-08-19
lovecodeblog 2020-08-19
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09
zhushenghan 2020-11-09
sunnnyduan 2020-10-16
不要皱眉 2020-10-14
xiaohai 2020-09-29
songxiugongwang 2020-09-22
萌亖 2020-09-17
LuckyLXG 2020-09-08
sdmzhu 2020-09-01
mkhhxxttxs 2020-09-16
xiaohai 2020-09-16
newcome 2020-09-09