add method

This commit is contained in:
Looly
2020-09-15 15:17:42 +08:00
parent 37b051a46c
commit b2e1b903ab
4 changed files with 56 additions and 34 deletions

View File

@@ -14,6 +14,7 @@
* 【core 】 增加TransXXXissue#I1TU1Y@Gitee
* 【core 】 增加Generator
* 【db 】 Column增加是否主键、保留位数等字段
* 【cache 】 Cache接口增加get重载issue#1080@Github
### Bug修复
* 【core 】 修复Dict.of错误issue#I1UUO5@Gitee

View File

@@ -1,18 +1,17 @@
package cn.hutool.cache;
import java.io.Serializable;
import java.util.Iterator;
import cn.hutool.cache.impl.CacheObj;
import cn.hutool.core.lang.func.Func0;
import java.io.Serializable;
import java.util.Iterator;
/**
* 缓存接口
*
* @author Looly,jodd
*
* @param <K> 键类型
* @param <V> 值类型
* @author Looly, jodd
*/
public interface Cache<K, V> extends Iterable<V>, Serializable {
@@ -61,16 +60,38 @@ public interface Cache<K, V> extends Iterable<V>, Serializable {
* @return 键对应的对象
* @see #get(Object, boolean)
*/
V get(K key);
default V get(K key) {
return get(key, true);
}
/**
* 从缓存中获得对象当对象不在缓存中或已经过期返回Func0回调产生的对象
* <p>
* 调用此方法时,会检查上次调用时间,如果与当前时间差值大于超时时间返回<code>null</code>,否则返回值。
* <p>
* 每次调用此方法会刷新最后访问时间,也就是说会重新计算超时时间。
*
* @param key 键
* @param supplier 如果不存在回调方法,用于生产值对象
* @return 值对象
*/
V get(K key, Func0<V> supplier);
default V get(K key, Func0<V> supplier) {
return get(key, true, supplier);
}
/**
* 从缓存中获得对象当对象不在缓存中或已经过期返回Func0回调产生的对象
* <p>
* 调用此方法时,会检查上次调用时间,如果与当前时间差值大于超时时间返回<code>null</code>,否则返回值。
* <p>
* 每次调用此方法会刷新最后访问时间,也就是说会重新计算超时时间。
*
* @param key 键
* @param isUpdateLastAccess 是否更新最后访问时间,即重新计算超时时间。
* @param supplier 如果不存在回调方法,用于生产值对象
* @return 值对象
*/
V get(K key, boolean isUpdateLastAccess, Func0<V> supplier);
/**
* 从缓存中获得对象,当对象不在缓存中或已经过期返回<code>null</code>

View File

@@ -125,13 +125,8 @@ public abstract class AbstractCache<K, V> implements Cache<K, V> {
}
@Override
public V get(K key) {
return get(key, true);
}
@Override
public V get(K key, Func0<V> supplier) {
V v = get(key);
public V get(K key, boolean isUpdateLastAccess, Func0<V> supplier) {
V v = get(key, isUpdateLastAccess);
if (null == v && null != supplier) {
final long stamp = lock.writeLock();
try {

View File

@@ -52,6 +52,11 @@ public class NoCache<K, V> implements Cache<K, V> {
@Override
public V get(K key, Func0<V> supplier) {
return get(key, true, supplier);
}
@Override
public V get(K key, boolean isUpdateLastAccess, Func0<V> supplier) {
try {
return (null == supplier) ? null : supplier.call();
} catch (Exception e) {