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);