Class RefreshAheadCache<K,V>
java.lang.Object
cloud.opencode.base.cache.RefreshAheadCache<K,V>
- Type Parameters:
K- key type | 键类型V- value type | 值类型Security | 安全性:
- Thread-safe: Yes - 线程安全: 是
- Null-safe: Partial (null values not allowed) - 空值安全: 部分(不允许 null 值)
- All Implemented Interfaces:
Cache<K,V>
Refresh Ahead Cache - Proactive cache refresh decorator
提前刷新缓存 - 主动缓存刷新装饰器
Wraps an existing cache to automatically refresh entries before they expire, ensuring cache hits even during refresh. This prevents cache stampede and improves latency by refreshing entries in the background.
包装现有缓存以在条目过期前自动刷新,确保在刷新期间仍能命中缓存。 这可以防止缓存击穿并通过后台刷新提高延迟性能。
Features | 主要功能:
- Proactive refresh before expiration - 过期前主动刷新
- Background async refresh - 后台异步刷新
- Stale-while-revalidate pattern - 验证时提供过期数据模式
- Configurable refresh policy - 可配置的刷新策略
- Single-flight refresh prevention - 单次刷新防止重复
Usage Examples | 使用示例:
// Create cache with refresh-ahead
Cache<String, User> cache = OpenCache.getOrCreate("users");
RefreshAheadCache<String, User> refreshCache = RefreshAheadCache.wrap(cache)
.refreshPolicy(RefreshAheadPolicy.percentageOfTtl(0.8))
.loader(key -> userService.findById(key))
.ttl(Duration.ofMinutes(30))
.build();
// Value will be refreshed in background when 80% of TTL has elapsed
User user = refreshCache.get("user:1");
// With custom executor
RefreshAheadCache<String, User> refreshCache = RefreshAheadCache.wrap(cache)
.refreshPolicy(RefreshAheadPolicy.beforeExpiration(Duration.ofSeconds(30)))
.loader(key -> userService.findById(key))
.executor(Executors.newVirtualThreadPerTaskExecutor())
.build();
- Since:
- JDK 25, opencode-base-cache V2.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classBuilder for RefreshAheadCachestatic final recordRefresh statistics record 刷新统计记录 -
Method Summary
Modifier and TypeMethodDescriptionasMap()Get a concurrent map view of this cache 获取 ConcurrentMap 视图AsyncCache<K, V> async()Get async view of this cache 获取异步视图intCancel all pending refreshes 取消所有待处理的刷新booleancancelPendingRefresh(K key) Cancel a pending refresh for a specific key 取消特定键的待处理刷新voidcleanUp()Perform cleanup (expired entries, etc.)Compute a new value for the key 计算键的新值computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) Compute a new value if key is present 如果键存在则计算新值booleancontainsKey(K key) Check if key exists 检查键是否存在entries()Get snapshot of all entries 获取所有条目的快照longGet estimated entry count (fast) 获取估算条目数(快速)forceRefresh(K key) Force refresh a specific key 强制刷新特定键Get value by key, returns null if not present 根据键获取值,不存在返回 nullGet value by key, load using loader if not present 根据键获取值,不存在时通过 loader 加载Get all values for given keys, returns only existing entries 批量获取,仅返回存在的条目Get all values, load missing keys using loader 批量获取,缺失的键通过 loader 加载getAndRemove(K key) Get value and remove the entry atomically 原子地获取值并删除条目intGet count of in-flight refreshes 获取正在进行的刷新数量getOrDefault(K key, V defaultValue) Get value or return default if not present 获取值,不存在则返回默认值Get refresh statistics 获取刷新统计voidinvalidate(K key) Invalidate a single key 使单个键失效voidInvalidate all entries 清空所有缓存voidinvalidateAll(Iterable<? extends K> keys) Invalidate multiple keys 批量失效booleanisRefreshInProgress(K key) Check if a refresh is in progress for a specific key 检查特定键是否正在刷新keys()Get snapshot of all keys 获取所有键的快照metrics()Get detailed cache metrics with latency percentiles 获取带延迟百分位数的详细缓存指标name()Get cache name 获取缓存名称voidPut a key-value pair into cache 放入键值对voidPut all key-value pairs into cache 批量放入voidputAllWithTtl(Map<? extends K, ? extends V> map, Duration ttl) Put all entries with custom TTL 批量放入并指定自定义 TTLbooleanputIfAbsent(K key, V value) Put if the key is absent, returns true if successful 不存在时放入,成功返回 truebooleanputIfAbsentWithTtl(K key, V value, Duration ttl) Put if absent with custom TTL 不存在时放入并指定自定义 TTLvoidputWithTtl(K key, V value, Duration ttl) Put a key-value pair with custom TTL (overrides default expiration) 放入键值对并指定自定义 TTL(覆盖默认过期时间)Replace value only if key is present 仅在键存在时替换值booleanReplace value only if current value equals expected value 仅在当前值等于期望值时替换voidshutdown()Shutdown the refresh-ahead cache, cancelling pending refreshes and releasing resources 关闭提前刷新缓存,取消待处理的刷新并释放资源longsize()Get exact entry count (may be slow) 获取精确条目数(可能较慢)stats()Get cache statistics 获取缓存统计信息values()Get snapshot of all values 获取所有值的快照static <K,V> RefreshAheadCache.Builder <K, V> Wrap a cache with refresh-ahead behavior 使用提前刷新行为包装缓存Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface Cache
clear, computeIfAbsent, containsValue, entryIterator, entryParallelStream, entryStream, forEach, forEachKey, forEachValue, getByPattern, getIfPresent, getOptional, getOrNull, invalidateByPattern, invalidateByValue, invalidateIf, isEmpty, keyIterator, keyParallelStream, keyStream, merge, putAllIfAbsent, putIfPresent, removeIfEquals, removeIfPresent, replaceAll, resetStats, updateAll, updateTtl, updateTtl, updateTtlAll, valueParallelStream, valueStream
-
Method Details
-
wrap
Wrap a cache with refresh-ahead behavior 使用提前刷新行为包装缓存- Type Parameters:
K- key type | 键类型V- value type | 值类型- Parameters:
cache- cache to wrap | 要包装的缓存- Returns:
- builder | 构建器
-
get
-
get
Description copied from interface:CacheGet value by key, load using loader if not present 根据键获取值,不存在时通过 loader 加载 -
getOrDefault
Description copied from interface:CacheGet value or return default if not present 获取值,不存在则返回默认值- Specified by:
getOrDefaultin interfaceCache<K,V> - Parameters:
key- the key | 键defaultValue- the default value | 默认值- Returns:
- the value or default | 值或默认值
-
put
-
putAll
-
putIfAbsent
Description copied from interface:CachePut if the key is absent, returns true if successful 不存在时放入,成功返回 true- Specified by:
putIfAbsentin interfaceCache<K,V> - Parameters:
key- the key | 键value- the value | 值- Returns:
- true if put successfully | 成功放入返回 true
-
putWithTtl
Description copied from interface:CachePut a key-value pair with custom TTL (overrides default expiration) 放入键值对并指定自定义 TTL(覆盖默认过期时间)- Specified by:
putWithTtlin interfaceCache<K,V> - Parameters:
key- the key | 键value- the value | 值ttl- the time-to-live for this entry | 此条目的存活时间
-
putAllWithTtl
Description copied from interface:CachePut all entries with custom TTL 批量放入并指定自定义 TTL- Specified by:
putAllWithTtlin interfaceCache<K,V> - Parameters:
map- the key-value pairs | 键值对 Mapttl- the time-to-live for all entries | 所有条目的存活时间
-
putIfAbsentWithTtl
Description copied from interface:CachePut if absent with custom TTL 不存在时放入并指定自定义 TTL- Specified by:
putIfAbsentWithTtlin interfaceCache<K,V> - Parameters:
key- the key | 键value- the value | 值ttl- the time-to-live | 存活时间- Returns:
- true if put successfully | 成功放入返回 true
-
getAll
-
getAll
-
computeIfPresent
Description copied from interface:CacheCompute a new value if key is present 如果键存在则计算新值If the key is present and the remapping function returns non-null, the value is replaced. If the function returns null, the entry is removed.
如果键存在且映射函数返回非 null,则替换值。如果函数返回 null,则删除条目。
- Specified by:
computeIfPresentin interfaceCache<K,V> - Parameters:
key- the key | 键remappingFunction- the function to compute new value | 计算新值的函数- Returns:
- the new value or null if removed/absent | 新值,如果被删除或不存在则返回 null
-
compute
Description copied from interface:CacheCompute a new value for the key 计算键的新值Atomically computes a new value. If the key is absent and the function returns non-null, a new entry is created. If the key is present and the function returns null, the entry is removed.
原子地计算新值。如果键不存在且函数返回非 null,则创建新条目。 如果键存在且函数返回 null,则删除条目。
-
getAndRemove
-
replace
-
replace
Description copied from interface:CacheReplace value only if current value equals expected value 仅在当前值等于期望值时替换 -
invalidate
-
invalidateAll
-
invalidateAll
public void invalidateAll()Description copied from interface:CacheInvalidate all entries 清空所有缓存- Specified by:
invalidateAllin interfaceCache<K,V>
-
containsKey
-
size
-
estimatedSize
public long estimatedSize()Description copied from interface:CacheGet estimated entry count (fast) 获取估算条目数(快速)- Specified by:
estimatedSizein interfaceCache<K,V> - Returns:
- estimated count | 估算数量
-
keys
-
values
-
entries
-
asMap
-
stats
-
metrics
-
cleanUp
-
async
-
name
-
getRefreshStats
Get refresh statistics 获取刷新统计- Returns:
- refresh stats | 刷新统计
-
forceRefresh
Force refresh a specific key 强制刷新特定键- Parameters:
key- the key to refresh | 要刷新的键- Returns:
- future with new value | 包含新值的 Future
-
cancelPendingRefresh
Cancel a pending refresh for a specific key 取消特定键的待处理刷新- Parameters:
key- the key to cancel refresh for | 要取消刷新的键- Returns:
- true if a refresh was cancelled | 如果取消了刷新返回 true
- Since:
- V2.0.1
-
cancelAllPendingRefreshes
public int cancelAllPendingRefreshes()Cancel all pending refreshes 取消所有待处理的刷新- Returns:
- count of cancelled refreshes | 取消的刷新数量
- Since:
- V2.0.1
-
shutdown
public void shutdown()Shutdown the refresh-ahead cache, cancelling pending refreshes and releasing resources 关闭提前刷新缓存,取消待处理的刷新并释放资源- Since:
- V2.0.6
-
isRefreshInProgress
Check if a refresh is in progress for a specific key 检查特定键是否正在刷新- Parameters:
key- the key to check | 要检查的键- Returns:
- true if refresh is in progress | 正在刷新返回 true
- Since:
- V2.0.1
-
getInFlightRefreshCount
public int getInFlightRefreshCount()Get count of in-flight refreshes 获取正在进行的刷新数量- Returns:
- count of in-flight refreshes | 进行中的刷新数量
- Since:
- V2.0.1
-