优化前
Object result = null;
String cacheLock = CacheUtil.genLockKey(cacheKey);
if (lock.lock(cacheLock, 5000, TimeUnit.MILLISECONDS)) {
try {
result = pjp.proceed();
if (Objects.nonNull(result)) {
rwxCache.set(cacheKey, JSON.toJSONString(result), 1, TimeUnit.HOURS);
}
} catch (Exception e) {
e.printStackTrace();
rwxCache.del(cacheKey);
} finally {
lock.unlock(cacheLock);
}
} else {
Future<String> future = taskExecutor.submit(() -> rwxCache.get(cacheKey));
try {
cache = future.get(500, TimeUnit.MILLISECONDS);
result = JSON.parseObject(cache, getReturnType(pjp));
} catch (Exception e) {
e.printStackTrace();
rwxCache.del(cacheKey);
}
}
return result;
优化后
Object result = null;
String cacheLock = CacheUtil.genLockKey(cacheKey);
if (lock.lock(cacheLock, 5000, TimeUnit.MILLISECONDS)) {
LOGGER.debug("[CacheFilterAspect] cache lock get. key={}", cacheKey);
try {
result = pjp.proceed();
if (Objects.nonNull(result)) {
rwxCache.set(cacheKey, JSON.toJSONString(result), 1, TimeUnit.HOURS);
}
} catch (Exception e) {
e.printStackTrace();
rwxCache.del(cacheKey);
} finally {
lock.unlock(cacheLock);
}
} else {
LOGGER.info("[CacheFilterAspect] cache async get. key={}", cacheKey);
Future<String> future = taskExecutor.submit(() -> {
while (true) {
if (!lock.isLocked(cacheLock)) {
return rwxCache.get(cacheKey);
} else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
LOGGER.error("[CacheRemoveAspect] interval wait error.", e);
throw e;
}
}
}
});
try {
cache = future.get(500, TimeUnit.MILLISECONDS);
result = JSON.parseObject(cache, getReturnType(pjp));
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("[CacheFilterAspect] cache async get timeout failed.");
throw e;
}
}
return result;