增加获取缓存对象方法

This commit is contained in:
gltqe 2025-03-24 15:51:15 +08:00
parent d254f7670d
commit 52958fee78
3 changed files with 69 additions and 4 deletions

View File

@ -186,4 +186,21 @@ public interface Cache<K, V> extends Iterable<V>, Serializable {
default Cache<K, V> setListener(CacheListener<K, V> listener){ default Cache<K, V> setListener(CacheListener<K, V> listener){
return this; return this;
} }
/**
* 获取缓存对象
*
* @param key
* @return 值或null
*/
CacheObj<K, V> getObj(K key);
/**
* 获取缓存对象
*
* @param isUpdateLastAccess 是否更新最后访问时间
* @param key
* @return 值或null
*/
CacheObj<K, V> getObj(K key, boolean isUpdateLastAccess);
} }

View File

@ -120,4 +120,13 @@ public class NoCache<K, V> implements Cache<K, V> {
return false; return false;
} }
@Override
public CacheObj<K, V> getObj(K key) {
return null;
}
@Override
public CacheObj<K, V> getObj(K key, boolean isUpdateLastAccess) {
return null;
}
} }

View File

@ -105,6 +105,22 @@ public abstract class ReentrantCache<K, V> extends AbstractCache<K, V> {
* @return 值或null * @return 值或null
*/ */
private V getOrRemoveExpired(final K key, final boolean isUpdateLastAccess, final boolean isUpdateCount) { private V getOrRemoveExpired(final K key, final boolean isUpdateLastAccess, final boolean isUpdateCount) {
CacheObj<K, V> co = getOrRemoveExpiredObj(key, isUpdateLastAccess, isUpdateCount);
if (co != null) {
return co.get(isUpdateLastAccess);
}
return null;
}
/**
* 获得值或清除过期值
*
* @param key
* @param isUpdateLastAccess 是否更新最后访问时间
* @param isUpdateCount 是否更新计数器
* @return 值或null
*/
private CacheObj<K, V> getOrRemoveExpiredObj(final K key, final boolean isUpdateLastAccess, final boolean isUpdateCount) {
CacheObj<K, V> co; CacheObj<K, V> co;
lock.lock(); lock.lock();
try { try {
@ -130,6 +146,29 @@ public abstract class ReentrantCache<K, V> extends AbstractCache<K, V> {
if (isUpdateCount) { if (isUpdateCount) {
hitCount.increment(); hitCount.increment();
} }
return co.get(isUpdateLastAccess); return co;
}
/**
* 获取缓存对象
*
* @param key
* @return 值或null
*/
@Override
public CacheObj<K, V> getObj(K key) {
return getOrRemoveExpiredObj(key, false, true);
}
/**
* 获取缓存对象
*
* @param isUpdateLastAccess 是否更新最后访问时间
* @param key
* @return 值或null
*/
@Override
public CacheObj<K, V> getObj(K key, boolean isUpdateLastAccess) {
return getOrRemoveExpiredObj(key, isUpdateLastAccess, true);
} }
} }