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

public interface DistributedCache<K,V> extends 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:
  • Method Details

    • get

      Optional<V> get(K key)
      Gets a value by key. 根据键获取值。
      Parameters:
      key - the key - 键
      Returns:
      Optional containing the value if present - 包含值的 Optional(如果存在)
    • getOrLoad

      V getOrLoad(K key, Function<K,V> loader, Duration ttl)
      Gets a value by key, or loads it using the provided function if absent. 根据键获取值,如果不存在则使用提供的函数加载。
      Parameters:
      key - the key - 键
      loader - the loader function - 加载函数
      ttl - the TTL for loaded value - 加载值的 TTL
      Returns:
      the value - 值
    • getAll

      Map<K,V> getAll(Collection<K> keys)
      Gets multiple values by keys. 根据多个键获取多个值。
      Parameters:
      keys - the keys - 键集合
      Returns:
      map of existing key-value pairs - 存在的键值对映射
    • put

      void put(K key, V value)
      Puts a value with default TTL. 使用默认 TTL 放入值。
      Parameters:
      key - the key - 键
      value - the value - 值
    • put

      void put(K key, V value, Duration ttl)
      Puts a value with specific TTL. 使用指定 TTL 放入值。
      Parameters:
      key - the key - 键
      value - the value - 值
      ttl - the time-to-live - 存活时间
    • putAll

      void putAll(Map<K,V> entries)
      Puts multiple key-value pairs with default TTL. 使用默认 TTL 放入多个键值对。
      Parameters:
      entries - the entries - 条目映射
    • putAll

      void putAll(Map<K,V> entries, Duration ttl)
      Puts multiple key-value pairs with specific TTL. 使用指定 TTL 放入多个键值对。
      Parameters:
      entries - the entries - 条目映射
      ttl - the time-to-live - 存活时间
    • putIfAbsent

      boolean putIfAbsent(K key, V value, Duration ttl)
      Puts a value only if the key doesn't exist. 仅在键不存在时放入值。
      Parameters:
      key - the key - 键
      value - the value - 值
      ttl - the time-to-live - 存活时间
      Returns:
      true if put successfully - 成功放入返回 true
    • remove

      boolean remove(K key)
      Removes a key. 删除键。
      Parameters:
      key - the key - 键
      Returns:
      true if removed - 删除成功返回 true
    • removeAll

      long removeAll(Collection<K> keys)
      Removes multiple keys. 删除多个键。
      Parameters:
      keys - the keys - 键集合
      Returns:
      count of removed keys - 删除的键数量
    • exists

      boolean exists(K key)
      Checks if a key exists. 检查键是否存在。
      Parameters:
      key - the key - 键
      Returns:
      true if exists - 存在返回 true
    • getTtl

      Optional<Duration> getTtl(K key)
      Gets the remaining TTL for a key. 获取键的剩余 TTL。
      Parameters:
      key - the key - 键
      Returns:
      Optional containing TTL, empty if key doesn't exist - 包含 TTL 的 Optional,键不存在则为空
    • setTtl

      boolean setTtl(K key, Duration ttl)
      Updates the TTL for an existing key. 更新现有键的 TTL。
      Parameters:
      key - the key - 键
      ttl - the new TTL - 新的 TTL
      Returns:
      true if updated - 更新成功返回 true
    • getAsync

      CompletableFuture<Optional<V>> getAsync(K key)
      Gets a value asynchronously. 异步获取值。
      Parameters:
      key - the key - 键
      Returns:
      CompletableFuture with Optional value - 包含 Optional 值的 CompletableFuture
    • getAllAsync

      CompletableFuture<Map<K,V>> getAllAsync(Collection<K> keys)
      Gets multiple values asynchronously. 异步获取多个值。
      Parameters:
      keys - the keys - 键集合
      Returns:
      CompletableFuture with map of values - 包含值映射的 CompletableFuture
    • putAsync

      CompletableFuture<Void> putAsync(K key, V value, Duration ttl)
      Puts a value asynchronously. 异步放入值。
      Parameters:
      key - the key - 键
      value - the value - 值
      ttl - the TTL - 存活时间
      Returns:
      CompletableFuture that completes when done - 完成时完成的 CompletableFuture
    • removeAsync

      CompletableFuture<Boolean> removeAsync(K key)
      Removes a key asynchronously. 异步删除键。
      Parameters:
      key - the key - 键
      Returns:
      CompletableFuture with removal result - 包含删除结果的 CompletableFuture
    • increment

      long increment(K key, long delta)
      Atomically increments a numeric value. 原子地增加数值。
      Parameters:
      key - the key - 键
      delta - the increment amount - 增量
      Returns:
      the new value - 新值
    • decrement

      default long decrement(K key, long delta)
      Atomically decrements a numeric value. 原子地减少数值。
      Parameters:
      key - the key - 键
      delta - the decrement amount - 减量
      Returns:
      the new value - 新值
    • compareAndSwap

      boolean compareAndSwap(K key, V expectedValue, V newValue, Duration ttl)
      Compare-and-swap operation. 比较并交换操作。
      Parameters:
      key - the key - 键
      expectedValue - the expected current value - 期望的当前值
      newValue - the new value - 新值
      ttl - the TTL for new value - 新值的 TTL
      Returns:
      true if swapped - 交换成功返回 true
    • keys

      Set<K> keys(String pattern)
      Gets all keys matching a pattern. 获取匹配模式的所有键。

      Pattern syntax depends on the backend (e.g., Redis uses glob patterns).

      模式语法取决于后端(例如 Redis 使用 glob 模式)。

      Parameters:
      pattern - the pattern - 模式
      Returns:
      set of matching keys - 匹配的键集合
    • scan

      DistributedCache.ScanResult<K> scan(String pattern, String cursor, int count)
      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

      long removeByPattern(String pattern)
      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

      Optional<DistributedCache.DistributedLock> lock(K lockKey, Duration ttl, Duration waitTime)
      Acquires a distributed lock, waiting up to the specified time. 获取分布式锁,最多等待指定时间。
      Parameters:
      lockKey - the lock key - 锁键
      ttl - the lock TTL - 锁 TTL
      waitTime - maximum time to wait - 最大等待时间
      Returns:
      the lock handle, or empty if timeout - 锁句柄,超时则为空
    • publish

      void publish(String channel, String message)
      Publishes a cache invalidation message. 发布缓存失效消息。
      Parameters:
      channel - the channel - 频道
      message - the message - 消息
    • subscribe

      DistributedCache.Subscription subscribe(String channel, Consumer<String> handler)
      Subscribes to cache invalidation messages. 订阅缓存失效消息。
      Parameters:
      channel - the channel - 频道
      handler - the message handler - 消息处理器
      Returns:
      subscription handle - 订阅句柄
    • stats

      Gets cache statistics. 获取缓存统计。
      Returns:
      the statistics - 统计信息
    • isHealthy

      boolean isHealthy()
      Checks if the cache is connected and healthy. 检查缓存是否已连接且健康。
      Returns:
      true if healthy - 健康返回 true
    • name

      String name()
      Gets the cache name. 获取缓存名称。
      Returns:
      the name - 名称
    • close

      void close()
      Closes the cache connection. 关闭缓存连接。
      Specified by:
      close in interface AutoCloseable