Class WriteBehindCache<K,V>
java.lang.Object
cloud.opencode.base.cache.WriteBehindCache<K,V>
- Type Parameters:
K- the type of keys | 键类型V- the type of values | 值类型Security | 安全性:
- Thread-safe: Yes - 线程安全: 是
- Null-safe: Partial (null values not allowed) - 空值安全: 部分(不允许 null 值)
- All Implemented Interfaces:
Cache<K,V>, AutoCloseable
Write-Behind Cache - Asynchronous batch persistence cache wrapper
写后缓存 - 异步批量持久化缓存包装器
Implements the Write-Behind (Write-Back) caching pattern where writes are collected and asynchronously persisted in batches, reducing write latency and database load.
实现写后(写回)缓存模式,写入操作被收集并异步批量持久化, 降低写入延迟和数据库负载。
Features | 主要功能:
- Asynchronous batch writes - 异步批量写入
- Write coalescing (multiple writes to same key) - 写合并
- Configurable batch size and flush interval - 可配置批量大小和刷新间隔
- Retry on write failure - 写入失败重试
- Graceful shutdown with flush - 优雅关闭并刷新
Usage Examples | 使用示例:
// Create write-behind cache - 创建写后缓存
Cache<String, User> cache = OpenCache.getOrCreate("users");
WriteBehindCache<String, User> writeBehind = WriteBehindCache.builder(cache)
.writer(users -> userRepository.saveAll(users))
.batchSize(100)
.flushInterval(Duration.ofSeconds(5))
.maxRetries(3)
.build();
// Writes are batched and persisted asynchronously
writeBehind.put("user:1", user1);
writeBehind.put("user:2", user2);
// Ensure all pending writes are flushed before shutdown
writeBehind.shutdown();
- Since:
- JDK 25, opencode-base-cache V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceBatch writer interface for persisting cache changes 批量写入器接口,用于持久化缓存变更static classBuilder for WriteBehindCache WriteBehindCache 构建器static final recordWrite-behind statistics 写后统计信息static final recordWrite failure information 写入失败信息 -
Method Summary
Modifier and TypeMethodDescriptionasMap()Get a concurrent map view of this cache 获取 ConcurrentMap 视图AsyncCache<K, V> async()Get async view of this cache 获取异步视图static <K,V> WriteBehindCache.Builder <K, V> Create a builder for WriteBehindCache 创建 WriteBehindCache 构建器voidcleanUp()Perform cleanup (expired entries, etc.)voidclose()booleancontainsKey(K key) Check if key exists 检查键是否存在entries()Get snapshot of all entries 获取所有条目的快照longGet estimated entry count (fast) 获取估算条目数(快速)voidflush()Force flush all pending writes immediately 立即强制刷新所有待写入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 加载voidinvalidate(K key) Invalidate a single key 使单个键失效voidInvalidate all entries 清空所有缓存voidinvalidateAll(Iterable<? extends K> keys) Invalidate multiple keys 批量失效keys()Get snapshot of all keys 获取所有键的快照metrics()Get detailed cache metrics with latency percentiles 获取带延迟百分位数的详细缓存指标name()Get cache name 获取缓存名称longGet count of pending writes 获取待写入数量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(覆盖默认过期时间)voidshutdown()Shutdown the write-behind cache, flushing pending writes 关闭写后缓存,刷新待写入voidShutdown with timeout 带超时关闭longsize()Get exact entry count (may be slow) 获取精确条目数(可能较慢)stats()Get cache statistics 获取缓存统计信息values()Get snapshot of all values 获取所有值的快照Get write-behind statistics 获取写后统计信息Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface Cache
clear, compute, computeIfAbsent, computeIfMatch, computeIfPresent, containsValue, entryIterator, entryParallelStream, entryStream, forEach, forEachKey, forEachValue, getAndRemove, getByPattern, getIfPresent, getOptional, getOrDefault, getOrNull, invalidateByPattern, invalidateByValue, invalidateIf, isEmpty, keyIterator, keyParallelStream, keyStream, merge, putAllIfAbsent, putIfPresent, removeIfEquals, removeIfPresent, replace, replace, replaceAll, replaceIf, resetStats, updateAll, updateTtl, updateTtl, updateTtlAll, valueParallelStream, valueStream
-
Method Details
-
builder
Create a builder for WriteBehindCache 创建 WriteBehindCache 构建器- Type Parameters:
K- key type | 键类型V- value type | 值类型- Parameters:
cache- the underlying cache | 底层缓存- Returns:
- builder | 构建器
-
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
-
invalidate
-
invalidateAll
-
invalidateAll
public void invalidateAll()Description copied from interface:CacheInvalidate all entries 清空所有缓存- Specified by:
invalidateAllin interfaceCache<K,V>
-
get
-
get
Description copied from interface:CacheGet value by key, load using loader if not present 根据键获取值,不存在时通过 loader 加载 -
getAll
-
getAll
-
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
-
pendingWriteCount
public long pendingWriteCount()Get count of pending writes 获取待写入数量- Returns:
- pending write count | 待写入数量
-
flush
public void flush()Force flush all pending writes immediately 立即强制刷新所有待写入 -
writeBehindStats
Get write-behind statistics 获取写后统计信息- Returns:
- write-behind stats | 写后统计
-
shutdown
public void shutdown()Shutdown the write-behind cache, flushing pending writes 关闭写后缓存,刷新待写入 -
shutdown
Shutdown with timeout 带超时关闭- Parameters:
timeout- maximum wait time | 最大等待时间
-
close
public void close()- Specified by:
closein interfaceAutoCloseable
-