private String getRealCacheKey(Cacheable cache, String value) { StringBuffer sb = new StringBuffer(); if (!cache.cacheClass().equals(Void.class)) { sb.append(cache.cacheClass().getName()).append("."); } if (!StringUtils.isEmpty(cache.prefix())) { sb.append(cache.prefix()).append("."); } sb.append(value); return sb.toString(); }
/** * 定义缓存逻辑 * * @throws Throwable */ @Around("@annotation(cn.ichano.common.cache.Cacheable)") public Object cache(ProceedingJoinPoint pjp) throws Throwable { Object result = null; Boolean cacheEnable = Env.getConfig().getBoolean("common.cache.enable", true); Method method = getMethod(pjp); // 如果参数是null,就无法取到对应的参数。 if (method == null) { return pjp.proceed(); } Cacheable cacheable = method.getAnnotation(Cacheable.class); LOGGER.debug("execute CacheAspect, invoke method:{} .", method.getName()); // 判断是否开启缓存 if (!cacheEnable || cacheable == null) { return pjp.proceed(); } // CacheKey cacheKey = findAnnotation(method); String realCacheKey = getRealCacheKey(pjp, cacheable); LOGGER.debug( "execute CacheAspect, invoke method:{},find cache key:{}", method.getName(), realCacheKey); if (StringUtils.isEmpty(realCacheKey)) { return pjp.proceed(); } // 获取方法的返回类型,让缓存可以返回正确的类型 // 使用redis 的hash进行存取,易于管理 if (cacheable.type().equals(Cacheable.Type.DELETE)) { lcCache.delValue(realCacheKey); cache.remove(realCacheKey); return pjp.proceed(); } else if (cacheable.type().equals(Cacheable.Type.QUERY)) { result = lcCache.getValue(realCacheKey); if (result != null) { return result; } result = cache.get(realCacheKey); if (result != null) { lcCache.setValue(realCacheKey, result); LOGGER.debug("cache query result. key:{}", realCacheKey); return result; } else { result = pjp.proceed(); LOGGER.debug("un find cache query result. key:{}", realCacheKey); cache.set(realCacheKey, result, cacheable.expireTime(), TimeUnit.SECONDS); boolean as = cache.hasKey(realCacheKey); lcCache.setValue(realCacheKey, result); } } else { // update // 更新或者查询失败,都需要再次设置值 result = pjp.proceed(); Object[] args = pjp.getArgs(); if (args.length == 1) { lcCache.setValue(realCacheKey, args[0]); cache.set(realCacheKey, args[0], cacheable.expireTime(), TimeUnit.SECONDS); LOGGER.debug("cache update entity. key:{},value:{}", realCacheKey, args[0]); } else { for (Object arg : args) { if (arg.getClass().equals(cacheable.cacheClass())) { lcCache.setValue(realCacheKey, arg); cache.set(realCacheKey, arg, cacheable.expireTime(), TimeUnit.SECONDS); LOGGER.debug("cache update entity. key:{},value:{}", realCacheKey, arg); break; } } } } return result; }
/** * 获取缓存的key值 * * @param pjp * @param cache * @return */ private String getRealCacheKey(ProceedingJoinPoint pjp, Cacheable cache) { String field = cache.field(); String value = getSpelKey(pjp, field); return getRealCacheKey(cache, value); }