add groupTimeInterval

This commit is contained in:
Looly
2020-11-28 23:29:10 +08:00
parent a09861b033
commit a302a11483
9 changed files with 282 additions and 35 deletions

View File

@@ -45,7 +45,6 @@ public interface Cache<K, V> extends Iterable<V>, Serializable {
* @param key 键
* @param object 缓存的对象
* @param timeout 失效时长,单位毫秒
* @see Cache#put(Object, Object, long)
*/
void put(K key, V object, long timeout);
@@ -159,4 +158,15 @@ public interface Cache<K, V> extends Iterable<V>, Serializable {
* @return 是否包含key
*/
boolean containsKey(K key);
/**
* 设置监听
*
* @param listener 监听
* @return this
* @since 5.5.2
*/
default Cache<K, V> setListener(CacheListener<K, V> listener){
return this;
}
}

View File

@@ -0,0 +1,20 @@
package cn.hutool.cache;
/**
* 缓存监听,用于实现缓存操作时的回调监听,例如缓存对象的移除事件等
*
* @param <K> 缓存键
* @param <V> 缓存值
* @author looly
* @since 5.5.2
*/
public interface CacheListener<K, V> {
/**
* 对象移除回调
*
* @param key 键
* @param cachedObject 被缓存的对象
*/
void onRemove(K key, V cachedObject);
}

View File

@@ -1,6 +1,7 @@
package cn.hutool.cache.impl;
import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheListener;
import cn.hutool.core.collection.CopiedIter;
import cn.hutool.core.lang.func.Func0;
@@ -51,6 +52,11 @@ public abstract class AbstractCache<K, V> implements Cache<K, V> {
*/
protected AtomicLong missCount = new AtomicLong();
/**
* 缓存监听
*/
protected CacheListener<K, V> listener;
// ---------------------------------------------------------------- put start
@Override
public void put(K key, V object) {
@@ -164,7 +170,7 @@ public abstract class AbstractCache<K, V> implements Cache<K, V> {
if (co.isExpired()) {
missCount.getAndIncrement();
} else{
} else {
// 命中
hitCount.getAndIncrement();
return co.get(isUpdateLastAccess);
@@ -280,13 +286,29 @@ public abstract class AbstractCache<K, V> implements Cache<K, V> {
// ---------------------------------------------------------------- common end
/**
* 对象移除回调。默认无动作
* 设置监听
*
* @param listener 监听
* @return this
* @since 5.5.2
*/
public AbstractCache<K, V> setListener(CacheListener<K, V> listener) {
this.listener = listener;
return this;
}
/**
* 对象移除回调。默认无动作<br>
* 子类可重写此方法用于监听移除事件如果重写listener将无效
*
* @param key 键
* @param cachedObject 被缓存的对象
*/
protected void onRemove(K key, V cachedObject) {
// ignore
final CacheListener<K, V> listener = this.listener;
if (null != listener) {
listener.onRemove(key, cachedObject);
}
}
/**

View File

@@ -18,6 +18,12 @@ public class CacheTest {
@Test
public void fifoCacheTest(){
Cache<String,String> fifoCache = CacheUtil.newFIFOCache(3);
fifoCache.setListener((key, value)->{
// 监听测试此测试中只有key1被移除测试是否监听成功
Assert.assertEquals("key1", key);
Assert.assertEquals("value1", value);
});
fifoCache.put("key1", "value1", DateUnit.SECOND.getMillis() * 3);
fifoCache.put("key2", "value2", DateUnit.SECOND.getMillis() * 3);
fifoCache.put("key3", "value3", DateUnit.SECOND.getMillis() * 3);