From 5bb7ec02b4d93453a903eb2d061e053cd53f4021 Mon Sep 17 00:00:00 2001 From: cheese8 Date: Wed, 6 Jul 2022 10:24:05 +0800 Subject: [PATCH] using guard clause to refactor CacheFilter (#10274) * using guard clause to refactor CacheFilter * Update CacheFilter.java --- .../dubbo/cache/filter/CacheFilter.java | 43 +++++++++++-------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java index 3122a8eee4..209776d3a5 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java @@ -91,26 +91,31 @@ public class CacheFilter implements Filter { */ @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - if (cacheFactory != null && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) { - Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation); - if (cache != null) { - String key = StringUtils.toArgumentString(invocation.getArguments()); - Object value = cache.get(key); - if (value != null) { - if (value instanceof ValueWrapper) { - return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation); - } else { - return AsyncRpcResult.newDefaultAsyncResult(value, invocation); - } - } - Result result = invoker.invoke(invocation); - if (!result.hasException()) { - cache.put(key, new ValueWrapper(result.getValue())); - } - return result; - } + if (cacheFactory == null || ConfigUtils.isEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) { + return invoker.invoke(invocation); } - return invoker.invoke(invocation); + Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation); + if (cache == null) { + return invoker.invoke(invocation); + } + String key = StringUtils.toArgumentString(invocation.getArguments()); + Object value = cache.get(key); + return (value != null) ? onCacheValuePresent(invocation, value) : onCacheValueNotPresent(invoker, invocation, cache, key); + } + + private Result onCacheValuePresent(Invocation invocation, Object value) { + if (value instanceof ValueWrapper) { + return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation); + } + return AsyncRpcResult.newDefaultAsyncResult(value, invocation); + } + + private Result onCacheValueNotPresent(Invoker invoker, Invocation invocation, Cache cache, String key) { + Result result = invoker.invoke(invocation); + if (!result.hasException()) { + cache.put(key, new ValueWrapper(result.getValue())); + } + return result; } /**