From 66baca51d777aa583ae2a20494b036ce9cc1a9e3 Mon Sep 17 00:00:00 2001 From: Redkale <22250530@qq.com> Date: Thu, 25 Jan 2018 14:24:28 +0800 Subject: [PATCH] =?UTF-8?q?CacheSource=E5=A2=9E=E5=8A=A0getIfAbsent?= =?UTF-8?q?=E7=B3=BB=E5=88=97=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/org/redkale/source/CacheSource.java | 45 +++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/org/redkale/source/CacheSource.java b/src/org/redkale/source/CacheSource.java index 7833e394a..3ec8aaaf9 100644 --- a/src/org/redkale/source/CacheSource.java +++ b/src/org/redkale/source/CacheSource.java @@ -8,6 +8,7 @@ package org.redkale.source; import java.lang.reflect.Type; import java.util.*; import java.util.concurrent.*; +import java.util.function.Function; import org.redkale.convert.ConvertColumn; import org.redkale.convert.json.JsonFactory; import org.redkale.util.ConstructorParameters; @@ -36,8 +37,26 @@ public interface CacheSource { public V get(final String key); + default V getIfAbsent(final String key, Function mappingFunction) { + V rs = get(key); + if (rs == null) { + rs = mappingFunction.apply(key); + if (rs != null) set(key, rs); + } + return rs; + } + public V getAndRefresh(final String key, final int expireSeconds); + default V getAndRefreshIfAbsent(final String key, final int expireSeconds, Function mappingFunction) { + V rs = getAndRefresh(key, expireSeconds); + if (rs == null) { + rs = mappingFunction.apply(key); + if (rs != null) set(expireSeconds, key, rs); + } + return rs; + } + public void refresh(final String key, final int expireSeconds); public void set(final String key, final V value); @@ -127,8 +146,34 @@ public interface CacheSource { public CompletableFuture getAsync(final String key); + default CompletableFuture getIfAbsentAsync(final String key, Function mappingFunction) { + return getAsync(key).thenCompose((V rs) -> { + if (rs == null) { + rs = mappingFunction.apply(key); + if (rs != null) { + final V v = rs; + return setAsync(key, rs).thenApply((k) -> v); + } + } + return CompletableFuture.completedFuture(rs); + }); + } + public CompletableFuture getAndRefreshAsync(final String key, final int expireSeconds); + default CompletableFuture getAndRefreshIfAbsentAsync(final String key, final int expireSeconds, Function mappingFunction) { + return getAndRefreshAsync(key, expireSeconds).thenCompose((V rs) -> { + if (rs == null) { + rs = mappingFunction.apply(key); + if (rs != null) { + final V v = rs; + return setAsync(expireSeconds, key, rs).thenApply((k) -> v); + } + } + return CompletableFuture.completedFuture(rs); + }); + } + public CompletableFuture refreshAsync(final String key, final int expireSeconds); public CompletableFuture setAsync(final String key, final V value);