Interface DistributedCache<K,V>
- Type Parameters:
K- the key type - 键类型V- the value type - 值类型Security | 安全性:
- Thread-safe: Implementation-dependent - 线程安全: 取决于实现
- Null-safe: Implementation-dependent - 空值安全: 取决于实现
- All Superinterfaces:
AutoCloseable
Distributed Cache Interface - Abstraction for remote caching systems
分布式缓存接口 - 远程缓存系统抽象
Provides a unified interface for distributed caching backends like Redis, Memcached, Hazelcast, etc. All operations are designed to work across network boundaries with proper error handling and timeout support.
为 Redis、Memcached、Hazelcast 等分布式缓存后端提供统一接口。 所有操作都设计为跨网络边界工作,具有适当的错误处理和超时支持。
Features | 主要功能:
- Synchronous and asynchronous APIs - 同步和异步 API
- TTL support for all entries - 所有条目的 TTL 支持
- Batch operations - 批量操作
- Atomic operations (CAS, increment) - 原子操作
- Key pattern scanning - 键模式扫描
- Distributed locking - 分布式锁
- Pub/Sub for cache invalidation - 用于缓存失效的发布/订阅
Usage Examples | 使用示例:
// Using Redis implementation
DistributedCache<String, User> cache = RedisCache.<String, User>builder()
.connection(redisClient)
.keyPrefix("user:")
.defaultTtl(Duration.ofHours(1))
.serializer(new JsonSerializer<>(User.class))
.build();
// Basic operations
cache.put("user:1001", user, Duration.ofHours(2));
Optional<User> user = cache.get("user:1001");
// Async operations
cache.getAsync("user:1001")
.thenAccept(user -> process(user));
// Atomic operations
long newValue = cache.increment("counter:views", 1);
// Distributed lock
try (var lock = cache.lock("resource:123", Duration.ofSeconds(30))) {
// Critical section
}
- Since:
- JDK 25, opencode-base-cache V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic interfaceHandle for a distributed lock.static final recordResult of a scan operation.static interfaceHandle for a subscription. -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Closes the cache connection.booleancompareAndSwap(K key, V expectedValue, V newValue, Duration ttl) Compare-and-swap operation.default longAtomically decrements a numeric value.booleanChecks if a key exists.Gets a value by key.getAll(Collection<K> keys) Gets multiple values by keys.getAllAsync(Collection<K> keys) Gets multiple values asynchronously.Gets a value asynchronously.Gets a value by key, or loads it using the provided function if absent.Gets the remaining TTL for a key.longAtomically increments a numeric value.booleanChecks if the cache is connected and healthy.Gets all keys matching a pattern.Acquires a distributed lock, waiting up to the specified time.name()Gets the cache name.voidPublishes a cache invalidation message.voidPuts a value with default TTL.voidPuts a value with specific TTL.voidPuts multiple key-value pairs with default TTL.voidPuts multiple key-value pairs with specific TTL.Puts a value asynchronously.booleanputIfAbsent(K key, V value, Duration ttl) Puts a value only if the key doesn't exist.booleanRemoves a key.longremoveAll(Collection<K> keys) Removes multiple keys.removeAsync(K key) Removes a key asynchronously.longremoveByPattern(String pattern) Removes all keys matching a pattern.Scans keys matching a pattern with cursor-based pagination.booleanUpdates the TTL for an existing key.stats()Gets cache statistics.Subscribes to cache invalidation messages.Acquires a distributed lock.
-
Method Details
-
get
-
getOrLoad
-
getAll
Gets multiple values by keys. 根据多个键获取多个值。- Parameters:
keys- the keys - 键集合- Returns:
- map of existing key-value pairs - 存在的键值对映射
-
put
-
put
-
putAll
-
putAll
-
putIfAbsent
-
remove
Removes a key. 删除键。- Parameters:
key- the key - 键- Returns:
- true if removed - 删除成功返回 true
-
removeAll
Removes multiple keys. 删除多个键。- Parameters:
keys- the keys - 键集合- Returns:
- count of removed keys - 删除的键数量
-
exists
Checks if a key exists. 检查键是否存在。- Parameters:
key- the key - 键- Returns:
- true if exists - 存在返回 true
-
getTtl
-
setTtl
-
getAsync
Gets a value asynchronously. 异步获取值。- Parameters:
key- the key - 键- Returns:
- CompletableFuture with Optional value - 包含 Optional 值的 CompletableFuture
-
getAllAsync
Gets multiple values asynchronously. 异步获取多个值。- Parameters:
keys- the keys - 键集合- Returns:
- CompletableFuture with map of values - 包含值映射的 CompletableFuture
-
putAsync
Puts a value asynchronously. 异步放入值。- Parameters:
key- the key - 键value- the value - 值ttl- the TTL - 存活时间- Returns:
- CompletableFuture that completes when done - 完成时完成的 CompletableFuture
-
removeAsync
Removes a key asynchronously. 异步删除键。- Parameters:
key- the key - 键- Returns:
- CompletableFuture with removal result - 包含删除结果的 CompletableFuture
-
increment
Atomically increments a numeric value. 原子地增加数值。- Parameters:
key- the key - 键delta- the increment amount - 增量- Returns:
- the new value - 新值
-
decrement
Atomically decrements a numeric value. 原子地减少数值。- Parameters:
key- the key - 键delta- the decrement amount - 减量- Returns:
- the new value - 新值
-
compareAndSwap
-
keys
-
scan
Scans keys matching a pattern with cursor-based pagination. 使用基于游标的分页扫描匹配模式的键。- Parameters:
pattern- the pattern - 模式cursor- the cursor (empty for first scan) - 游标(第一次扫描为空)count- hint for number of keys to return - 返回键数量的提示- Returns:
- scan result with keys and next cursor - 包含键和下一个游标的扫描结果
-
removeByPattern
Removes all keys matching a pattern. 删除匹配模式的所有键。- Parameters:
pattern- the pattern - 模式- Returns:
- count of removed keys - 删除的键数量
-
tryLock
Acquires a distributed lock. 获取分布式锁。- Parameters:
lockKey- the lock key - 锁键ttl- the lock TTL (auto-release time) - 锁 TTL(自动释放时间)- Returns:
- the lock handle, or empty if lock not acquired - 锁句柄,未获取则为空
-
lock
Acquires a distributed lock, waiting up to the specified time. 获取分布式锁,最多等待指定时间。- Parameters:
lockKey- the lock key - 锁键ttl- the lock TTL - 锁 TTLwaitTime- maximum time to wait - 最大等待时间- Returns:
- the lock handle, or empty if timeout - 锁句柄,超时则为空
-
publish
-
subscribe
Subscribes to cache invalidation messages. 订阅缓存失效消息。- Parameters:
channel- the channel - 频道handler- the message handler - 消息处理器- Returns:
- subscription handle - 订阅句柄
-
stats
-
isHealthy
boolean isHealthy()Checks if the cache is connected and healthy. 检查缓存是否已连接且健康。- Returns:
- true if healthy - 健康返回 true
-
name
-
close
-