Interface Cache<K,V>
- Type Parameters:
K- the type of keys | 键类型V- the type of values | 值类型
- All Known Subinterfaces:
LoadingCache<K,V>
- All Known Implementing Classes:
CacheTestSupport.MockCache, CacheTestSupport.RecordingCache, CompressedCache, CopyOnReadCache, LayeredCache, MultiLevelCache, NullSafeCache, ProtectedCache, ReadThroughCache, ReferenceCache, RefreshAheadCache, TimeoutCache, VariableTtlCache, WriteBehindCache, WriteThroughCache
Provides comprehensive cache operations including get, put, invalidate and statistics.
提供完整的缓存操作,包括获取、放入、失效和统计功能。
Features | 主要功能:
- Basic operations (get, put, invalidate) - 基本操作(获取、放入、失效)
- Batch operations (getAll, putAll, invalidateAll) - 批量操作
- Compute if absent with loader - 不存在时加载
- Statistics and monitoring - 统计与监控
- Async view support - 异步视图支持
Usage Examples | 使用示例:
// Get value - 获取值
User user = cache.get("user:1001");
// Get or load - 获取或加载
User user = cache.get("user:1001", key -> userService.findById(key));
// Put value - 放入值
cache.put("user:1001", user);
// Invalidate - 失效
cache.invalidate("user:1001");
Security | 安全性:
- Thread-safe: Yes - 线程安全: 是
- Null-safe: Partial (null values not allowed) - 空值安全: 部分(不允许 null 值)
- Since:
- JDK 25, opencode-base-cache V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionasMap()Get a concurrent map view of this cache 获取 ConcurrentMap 视图AsyncCache<K, V> async()Get async view of this cache 获取异步视图voidcleanUp()Perform cleanup (expired entries, etc.)default voidclear()Clear all entries (alias for invalidateAll, for Map API compatibility) 清空所有条目(invalidateAll 的别名,兼容 Map API)default VCompute a new value for the key 计算键的新值default VcomputeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) Compute value if absent (alias for get with loader for Map API compatibility) 不存在时计算值(为 Map API 兼容性提供的 get with loader 别名)default VcomputeIfPresent(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 检查键是否存在default booleancontainsValue(V value) Check if cache contains a specific value 检查缓存是否包含特定值entries()Get snapshot of all entries 获取所有条目的快照Get a lazy iterator over entries (memory efficient) 获取条目的惰性迭代器(内存高效)Get a parallel stream over entries 获取条目的并行流Get a lazy stream over entries (memory efficient) 获取条目的惰性流(内存高效)longGet estimated entry count (fast) 获取估算条目数(快速)default voidforEach(BiConsumer<? super K, ? super V> action) Iterate over all entries with a consumer (memory efficient) 使用消费者遍历所有条目(内存高效)default voidforEachKey(Consumer<? super K> action) Iterate over all keys with a consumer 使用消费者遍历所有键default voidforEachValue(Consumer<? super V> action) Iterate over all values with a consumer 使用消费者遍历所有值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 加载default VgetAndRemove(K key) Get value and remove the entry atomically 原子地获取值并删除条目getByPattern(String pattern) Get entries matching a key pattern 获取匹配键模式的条目getIfPresent(K key) Get value only if present, without triggering loader 仅在存在时获取值,不触发加载器getOptional(K key) Get value as Optional, distinguishing "not present" from "null value" 以 Optional 形式获取值,区分"不存在"和"值为 null"default VgetOrDefault(K key, V defaultValue) Get value or return default if not present 获取值,不存在则返回默认值default VGet value or null if not present (explicit null return) 获取值,不存在时显式返回 nullvoidinvalidate(K key) Invalidate a single key 使单个键失效voidInvalidate all entries 清空所有缓存voidinvalidateAll(Iterable<? extends K> keys) Invalidate multiple keys 批量失效default longinvalidateByPattern(String pattern) Invalidate entries matching a pattern (supports * and ?default longinvalidateByValue(Predicate<V> predicate) Invalidate entries matching a value predicate 使值满足条件的条目失效default longinvalidateIf(Predicate<K> predicate) Invalidate entries matching a predicate 使满足条件的条目失效default booleanisEmpty()Check if cache is empty 检查缓存是否为空Get a lazy iterator over keys (memory efficient) 获取键的惰性迭代器(内存高效)Get a parallel stream over keys 获取键的并行流keys()Get snapshot of all keys 获取所有键的快照Get a lazy stream over keys (memory efficient) 获取键的惰性流(内存高效)default VMerge a value with existing value using the given function 使用给定函数合并值与现有值default CacheMetricsmetrics()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 批量放入default intputAllIfAbsent(Map<? extends K, ? extends V> map) Put all entries if their keys are absent 批量放入不存在的键的条目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 不存在时放入并指定自定义 TTLdefault booleanputIfPresent(K key, V value) Put value only if key is present (update existing entry only) 仅在键存在时放入值(仅更新现有条目)voidputWithTtl(K key, V value, Duration ttl) Put a key-value pair with custom TTL (overrides default expiration) 放入键值对并指定自定义 TTL(覆盖默认过期时间)default booleanremoveIfEquals(K key, V value) Remove entry only if value matches the expected value 仅在值与期望值匹配时移除条目default booleanremoveIfPresent(K key) Remove entry only if key is present and return success status 仅在键存在时移除条目,并返回成功状态default VReplace value only if key is present 仅在键存在时替换值default booleanReplace value only if current value equals expected value 仅在当前值等于期望值时替换default intreplaceAll(BiFunction<? super K, ? super V, ? extends V> function) Replace all values using the given function 使用给定函数替换所有值default voidReset statistics counters 重置统计计数器longsize()Get exact entry count (may be slow) 获取精确条目数(可能较慢)stats()Get cache statistics 获取缓存统计信息default intUpdate only existing entries (does not insert new ones) 仅更新现有条目(不插入新条目)default longUpdate TTL for specific keys 更新指定键的 TTLdefault longUpdate TTL for existing entries matching predicate 更新匹配条件的现有条目的 TTLdefault longupdateTtlAll(Duration ttl) Update TTL for all entries 更新所有条目的 TTLGet a parallel stream over values 获取值的并行流values()Get snapshot of all values 获取所有值的快照Get a lazy stream over values (memory efficient) 获取值的惰性流(内存高效)
-
Method Details
-
get
-
get
-
getAll
-
getAll
-
put
-
putAll
-
putIfAbsent
-
putWithTtl
-
putAllWithTtl
-
putIfAbsentWithTtl
-
getOrDefault
-
computeIfPresent
Compute 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,则删除条目。
- Parameters:
key- the key | 键remappingFunction- the function to compute new value | 计算新值的函数- Returns:
- the new value or null if removed/absent | 新值,如果被删除或不存在则返回 null
-
compute
Compute 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,则删除条目。
- Parameters:
key- the key | 键remappingFunction- the function to compute value | 计算值的函数- Returns:
- the new value or null if removed | 新值,如果被删除则返回 null
-
getAndRemove
-
replace
-
replace
-
getOptional
Get value as Optional, distinguishing "not present" from "null value" 以 Optional 形式获取值,区分"不存在"和"值为 null"Unlike
get(Object), this method can distinguish between a key that is not present and a key that is present with a null value.与
get(Object)不同,此方法可以区分键不存在和键存在但值为 null 的情况。- Parameters:
key- the key | 键- Returns:
- Optional containing the value, or empty if key not present | 包含值的 Optional,键不存在则返回空
- Since:
- V2.0.2
-
getIfPresent
Get value only if present, without triggering loader 仅在存在时获取值,不触发加载器This is useful when you want to check the cache without side effects.
当您想检查缓存而不产生副作用时,此方法很有用。
- Parameters:
key- the key | 键- Returns:
- Optional containing the value, or empty if not present | 包含值的 Optional,不存在则返回空
- Since:
- V2.0.2
-
merge
Merge a value with existing value using the given function 使用给定函数合并值与现有值If the key is absent, the provided value is used. If the key is present, the merge function is called with the old and new values.
如果键不存在,使用提供的值。如果键存在,使用旧值和新值调用合并函数。
- Parameters:
key- the key | 键value- the value to merge | 要合并的值mergeFunction- the function to merge values | 合并函数- Returns:
- the new value | 新值
- Since:
- V2.0.2
-
computeIfAbsent
Compute value if absent (alias for get with loader for Map API compatibility) 不存在时计算值(为 Map API 兼容性提供的 get with loader 别名)- Parameters:
key- the key | 键mappingFunction- the function to compute value | 计算值的函数- Returns:
- the value | 值
- Since:
- V2.0.2
-
putIfPresent
Put value only if key is present (update existing entry only) 仅在键存在时放入值(仅更新现有条目)Unlike
put(Object, Object), this does not create a new entry if the key is not present.与
put(Object, Object)不同,如果键不存在则不创建新条目。- Parameters:
key- the key | 键value- the value | 值- Returns:
- true if updated, false if key was not present | 更新成功返回 true,键不存在返回 false
- Since:
- V2.0.3
-
containsValue
Check if cache contains a specific value 检查缓存是否包含特定值Warning: This operation is O(n) as it scans all values.
警告:此操作为 O(n),因为它扫描所有值。
- Parameters:
value- the value to check | 要检查的值- Returns:
- true if value exists | 值存在返回 true
- Since:
- V2.0.3
-
getOrNull
Get value or null if not present (explicit null return) 获取值,不存在时显式返回 nullThis is semantically equivalent to
get(Object)but makes the null return value explicit in the method name.这在语义上等同于
get(Object),但在方法名中明确表示返回 null。- Parameters:
key- the key | 键- Returns:
- the value or null | 值或 null
- Since:
- V2.0.3
-
replaceAll
Replace all values using the given function 使用给定函数替换所有值- Parameters:
function- the function to transform values | 转换值的函数- Returns:
- count of replaced entries | 替换的条目数
- Since:
- V2.0.3
-
forEachValue
-
forEachKey
-
removeIfPresent
Remove entry only if key is present and return success status 仅在键存在时移除条目,并返回成功状态- Parameters:
key- the key | 键- Returns:
- true if removed, false if key was not present | 移除成功返回 true,键不存在返回 false
- Since:
- V2.0.3
-
removeIfEquals
-
getByPattern
-
putAllIfAbsent
-
updateAll
-
invalidate
Invalidate a single key 使单个键失效- Parameters:
key- the key to invalidate | 要失效的键
-
invalidateAll
-
invalidateAll
void invalidateAll()Invalidate all entries 清空所有缓存 -
clear
default void clear()Clear all entries (alias for invalidateAll, for Map API compatibility) 清空所有条目(invalidateAll 的别名,兼容 Map API)- Since:
- V2.0.1
-
invalidateByPattern
Invalidate entries matching a pattern (supports * and ? wildcards) 使匹配模式的条目失效(支持 * 和 ? 通配符)Pattern syntax:
*- matches any sequence of characters?- matches any single character
Examples | 示例:
cache.invalidateByPattern("user:*"); // Invalidate all user entries cache.invalidateByPattern("*.temp"); // Invalidate entries ending with .temp cache.invalidateByPattern("session:???"); // Invalidate 3-char session IDs- Parameters:
pattern- the pattern to match (supports * and ? wildcards) | 匹配模式- Returns:
- count of invalidated entries | 失效的条目数
- Since:
- V1.9.0
-
invalidateIf
Invalidate entries matching a predicate 使满足条件的条目失效Examples | 示例:
// Invalidate all entries with keys starting with "temp:" cache.invalidateIf(key -> key.toString().startsWith("temp:")); // Invalidate entries with numeric keys greater than 1000 cache.invalidateIf(key -> ((Integer)key) > 1000);- Parameters:
predicate- the predicate to test keys | 键测试条件- Returns:
- count of invalidated entries | 失效的条目数
- Since:
- V1.9.0
-
invalidateByValue
-
containsKey
Check if key exists 检查键是否存在- Parameters:
key- the key | 键- Returns:
- true if exists | 存在返回 true
-
size
long size()Get exact entry count (may be slow) 获取精确条目数(可能较慢)- Returns:
- entry count | 条目数
-
estimatedSize
long estimatedSize()Get estimated entry count (fast) 获取估算条目数(快速)- Returns:
- estimated count | 估算数量
-
isEmpty
default boolean isEmpty()Check if cache is empty 检查缓存是否为空- Returns:
- true if empty | 为空返回 true
- Since:
- V2.0.1
-
keys
-
values
-
entries
-
asMap
ConcurrentMap<K,V> asMap()Get a concurrent map view of this cache 获取 ConcurrentMap 视图- Returns:
- concurrent map view | ConcurrentMap 视图
-
keyIterator
-
entryIterator
-
forEach
Iterate over all entries with a consumer (memory efficient) 使用消费者遍历所有条目(内存高效)- Parameters:
action- the action to perform | 要执行的操作- Since:
- V1.9.0
-
keyStream
Get a lazy stream over keys (memory efficient) 获取键的惰性流(内存高效)Creates a stream directly from the underlying map without creating intermediate collections. Ideal for large caches where collecting all keys would be expensive.
直接从底层映射创建流,不创建中间集合。适用于收集所有键成本较高的大型缓存。
- Returns:
- lazy stream over keys | 键的惰性流
- Since:
- V2.0.0
-
valueStream
-
entryStream
-
keyParallelStream
-
valueParallelStream
-
entryParallelStream
-
updateTtl
Update TTL for existing entries matching predicate 更新匹配条件的现有条目的 TTLNote: This re-puts entries with new TTL. Original values are preserved.
注意:这会用新的 TTL 重新放入条目。原始值保持不变。
- Parameters:
predicate- condition for keys to update | 要更新的键条件ttl- new TTL | 新的 TTL- Returns:
- count of updated entries | 更新的条目数
- Since:
- V1.9.0
-
updateTtlAll
Update TTL for all entries 更新所有条目的 TTL- Parameters:
ttl- new TTL | 新的 TTL- Returns:
- count of updated entries | 更新的条目数
- Since:
- V1.9.0
-
updateTtl
-
stats
-
metrics
Get detailed cache metrics with latency percentiles 获取带延迟百分位数的详细缓存指标- Returns:
- cache metrics or null if not enabled | 缓存指标,未启用则返回 null
-
resetStats
default void resetStats()Reset statistics counters 重置统计计数器Clears all hit, miss, load, and eviction counters to zero. Also resets metrics if enabled.
将所有命中、未命中、加载和淘汰计数器清零。如果启用,也重置指标。
- Since:
- V2.0.3
-
cleanUp
void cleanUp()Perform cleanup (expired entries, etc.) 执行清理(过期条目等) -
async
-
name
-