Cache增加get重载,可自定义超时时间

This commit is contained in:
Looly 2023-11-14 09:10:41 +08:00
parent fbe78688a1
commit 1b423b2e0f
3 changed files with 26 additions and 1 deletions

View File

@ -104,6 +104,21 @@ public interface Cache<K, V> extends Iterable<V>, Serializable {
*/
V get(K key, boolean isUpdateLastAccess, SerSupplier<V> supplier);
/**
* 从缓存中获得对象当对象不在缓存中或已经过期返回SerSupplier回调产生的对象
* <p>
* 调用此方法时会检查上次调用时间如果与当前时间差值大于超时时间返回{@code null}否则返回值
* <p>
* 每次调用此方法会可选是否刷新最后访问时间{@code true}表示会重新计算超时时间
*
* @param key
* @param isUpdateLastAccess 是否更新最后访问时间即重新计算超时时间
* @param timeout 自定义超时时间
* @param supplier 如果不存在回调方法用于生产值对象
* @return 值对象
*/
V get(K key, boolean isUpdateLastAccess, final long timeout, SerSupplier<V> supplier);
/**
* 从缓存中获得对象当对象不在缓存中或已经过期返回{@code null}
* <p>

View File

@ -121,6 +121,11 @@ public abstract class AbstractCache<K, V> implements Cache<K, V> {
@Override
public V get(final K key, final boolean isUpdateLastAccess, final SerSupplier<V> supplier) {
return get(key, isUpdateLastAccess, this.timeout, supplier);
}
@Override
public V get(final K key, final boolean isUpdateLastAccess, final long timeout, final SerSupplier<V> supplier) {
V v = get(key, isUpdateLastAccess);
if (null == v && null != supplier) {
//每个key单独获取一把锁降低锁的粒度提高并发能力see pr#1385@Github
@ -131,7 +136,7 @@ public abstract class AbstractCache<K, V> implements Cache<K, V> {
final CacheObj<K, V> co = getWithoutLock(key);
if (null == co || co.isExpired()) {
v = supplier.get();
put(key, v, this.timeout);
put(key, v, timeout);
} else {
v = co.get(isUpdateLastAccess);
}

View File

@ -69,6 +69,11 @@ public class NoCache<K, V> implements Cache<K, V> {
@Override
public V get(final K key, final boolean isUpdateLastAccess, final SerSupplier<V> supplier) {
return get(key, isUpdateLastAccess, 0, supplier);
}
@Override
public V get(final K key, final boolean isUpdateLastAccess, final long timeout, final SerSupplier<V> supplier) {
return (null == supplier) ? null : supplier.get();
}