Skip to content

Commit 8b4be5c

Browse files
committed
优化代码,避免产生遍历
1 parent 85067f5 commit 8b4be5c

1 file changed

Lines changed: 19 additions & 15 deletions

File tree

src/main/java/com/jarvis/cache/MagicHandler.java

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -259,17 +259,19 @@ private Map<CacheKeyTO, MSetParam> writeMagicCache(Object newValue) throws Excep
259259
}
260260

261261
/**
262-
* 参数的情况下,将所有从数据源加载的数据写入缓存
263-
* @param newValue 从数据源加载的数据
264-
* @param args 参数
262+
* 有参数的情况下,将所有从数据源加载的数据写入缓存
263+
*
264+
* @param newValue 从数据源加载的数据
265+
* @param args 参数
265266
* @param cacheValues 已经命中缓存数据
266-
* @param keyArgMap 缓存Key与参数的映射
267+
* @param keyArgMap 缓存Key与参数的映射
267268
* @return 返回所有未命中缓存的数据
268269
* @throws Exception
269270
*/
270271
private Map<CacheKeyTO, MSetParam> writeMagicCache(Object newValue, Object[] args, Map<CacheKeyTO, CacheWrapper<Object>> cacheValues, Map<CacheKeyTO, Object> keyArgMap) throws Exception {
271272
int cachedSize = null == cacheValues ? 0 : cacheValues.size();
272-
Map<CacheKeyTO, MSetParam> unmatchCache = new HashMap<>(keyArgMap.size() - cachedSize);
273+
int unmatchSize = keyArgMap.size() - cachedSize;
274+
Map<CacheKeyTO, MSetParam> unmatchCache = new HashMap<>(unmatchSize);
273275
if (null != newValue) {
274276
if (newValue.getClass().isArray()) {
275277
Object[] newValues = (Object[]) newValue;
@@ -287,17 +289,19 @@ private Map<CacheKeyTO, MSetParam> writeMagicCache(Object newValue, Object[] arg
287289
throw new Exception("Magic模式返回值,只允许是数组或Collection类型的");
288290
}
289291
}
290-
Set<CacheKeyTO> cacheKeySet = keyArgMap.keySet();
291-
// 为了避免缓存穿透问题,将数据源和缓存中都不存数据的Key,设置为null
292-
for (CacheKeyTO cacheKeyTO : cacheKeySet) {
293-
if (unmatchCache.containsKey(cacheKeyTO)) {
294-
continue;
295-
}
296-
if (null != cacheValues && cacheValues.containsKey(cacheKeyTO)) {
297-
continue;
292+
if (unmatchCache.size() < unmatchSize) {
293+
Set<CacheKeyTO> cacheKeySet = keyArgMap.keySet();
294+
// 为了避免缓存穿透问题,将数据源和缓存中都不存数据的Key,设置为null
295+
for (CacheKeyTO cacheKeyTO : cacheKeySet) {
296+
if (unmatchCache.containsKey(cacheKeyTO)) {
297+
continue;
298+
}
299+
if (null != cacheValues && cacheValues.containsKey(cacheKeyTO)) {
300+
continue;
301+
}
302+
MSetParam mSetParam = genCacheWrapper(cacheKeyTO, null, args);
303+
unmatchCache.put(mSetParam.getCacheKey(), mSetParam);
298304
}
299-
MSetParam mSetParam = genCacheWrapper(cacheKeyTO, null, args);
300-
unmatchCache.put(mSetParam.getCacheKey(), mSetParam);
301305
}
302306
if (null != unmatchCache && unmatchCache.size() > 0) {
303307
this.cacheHandler.mset(pjp.getMethod(), unmatchCache.values());

0 commit comments

Comments
 (0)