Class MultiLevelCache<K,V>

java.lang.Object
cloud.opencode.base.cache.multilevel.MultiLevelCache<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>

public class MultiLevelCache<K,V> extends Object implements Cache<K,V>
Multi-Level Cache - Supports 3+ levels with flexible configuration 多级缓存 - 支持 3 个以上级别的灵活配置

A flexible multi-level cache implementation that supports arbitrary number of cache levels with individual configurations.

灵活的多级缓存实现,支持任意数量的缓存级别,各级别可独立配置。

Features | 主要功能:

  • Unlimited cache levels - 无限缓存级别
  • Per-level TTL - 每级 TTL
  • Automatic promotion - 自动提升
  • Spillover handling - 溢出处理
  • Level-specific metrics - 级别特定指标

Usage Examples | 使用示例:

// Create 3-level cache: L1 (hot) -> L2 (warm) -> L3 (cold/remote)
MultiLevelCache<String, User> cache = MultiLevelCache.<String, User>builder()
    .level(LevelConfig.<String, User>builder()
        .name("L1-hot")
        .cache(hotCache)
        .ttl(Duration.ofMinutes(5))
        .promoteOnHit(true)
        .build())
    .level(LevelConfig.<String, User>builder()
        .name("L2-warm")
        .cache(warmCache)
        .ttl(Duration.ofMinutes(30))
        .promoteOnHit(true)
        .build())
    .level(LevelConfig.<String, User>builder()
        .name("L3-cold")
        .cache(coldCache)
        .ttl(Duration.ofHours(24))
        .build())
    .build();

// Use like normal cache
User user = cache.get("user:1001");  // Checks L1, L2, L3 in order
Since:
JDK 25, opencode-base-cache V2.0.5
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • builder

      public static <K,V> MultiLevelCache.Builder<K,V> builder()
      Create a builder 创建构建器
      Type Parameters:
      K - key type | 键类型
      V - value type | 值类型
      Returns:
      builder | 构建器
    • ofTwoLevel

      public static <K,V> MultiLevelCache<K,V> ofTwoLevel(Cache<K,V> l1, Cache<K,V> l2)
      Creates a two-level cache as a convenient replacement for LayeredCache. 创建两级缓存,作为 LayeredCache 的便捷替代。

      The returned cache uses MultiLevelCache.WritePolicy.WRITE_ALL and MultiLevelCache.InvalidationPolicy.INVALIDATE_ALL, with L2 promotion on hit enabled.

      返回的缓存使用 MultiLevelCache.WritePolicy.WRITE_ALLMultiLevelCache.InvalidationPolicy.INVALIDATE_ALL,并在 L2 命中时启用提升。

      Type Parameters:
      K - key type | 键类型
      V - value type | 值类型
      Parameters:
      l1 - L1 cache (fast, small) | L1 缓存(快速、小)
      l2 - L2 cache (slower, large) | L2 缓存(较慢、大)
      Returns:
      a two-level multi-level cache | 两级多级缓存
    • get

      public V get(K key)
      Description copied from interface: Cache
      Get value by key, returns null if not present 根据键获取值,不存在返回 null
      Specified by:
      get in interface Cache<K,V>
      Parameters:
      key - the key | 键
      Returns:
      the value or null | 值或 null
    • get

      public V get(K key, Function<? super K, ? extends V> loader)
      Description copied from interface: Cache
      Get value by key, load using loader if not present 根据键获取值,不存在时通过 loader 加载
      Specified by:
      get in interface Cache<K,V>
      Parameters:
      key - the key | 键
      loader - the loader function | 加载函数
      Returns:
      the value | 值
    • getAll

      public Map<K,V> getAll(Iterable<? extends K> keys)
      Description copied from interface: Cache
      Get all values for given keys, returns only existing entries 批量获取,仅返回存在的条目
      Specified by:
      getAll in interface Cache<K,V>
      Parameters:
      keys - the keys | 键集合
      Returns:
      map of existing entries | 存在的条目 Map
    • getAll

      public Map<K,V> getAll(Iterable<? extends K> keys, Function<? super Set<? extends K>, ? extends Map<K,V>> loader)
      Description copied from interface: Cache
      Get all values, load missing keys using loader 批量获取,缺失的键通过 loader 加载
      Specified by:
      getAll in interface Cache<K,V>
      Parameters:
      keys - the keys | 键集合
      loader - the batch loader function | 批量加载函数
      Returns:
      map of all entries | 所有条目 Map
    • put

      public void put(K key, V value)
      Description copied from interface: Cache
      Put a key-value pair into cache 放入键值对
      Specified by:
      put in interface Cache<K,V>
      Parameters:
      key - the key | 键
      value - the value | 值
    • putAll

      public void putAll(Map<? extends K, ? extends V> map)
      Description copied from interface: Cache
      Put all key-value pairs into cache 批量放入
      Specified by:
      putAll in interface Cache<K,V>
      Parameters:
      map - the key-value pairs | 键值对 Map
    • putIfAbsent

      public boolean putIfAbsent(K key, V value)
      Description copied from interface: Cache
      Put if the key is absent, returns true if successful 不存在时放入,成功返回 true
      Specified by:
      putIfAbsent in interface Cache<K,V>
      Parameters:
      key - the key | 键
      value - the value | 值
      Returns:
      true if put successfully | 成功放入返回 true
    • putWithTtl

      public void putWithTtl(K key, V value, Duration ttl)
      Description copied from interface: Cache
      Put a key-value pair with custom TTL (overrides default expiration) 放入键值对并指定自定义 TTL(覆盖默认过期时间)
      Specified by:
      putWithTtl in interface Cache<K,V>
      Parameters:
      key - the key | 键
      value - the value | 值
      ttl - the time-to-live for this entry | 此条目的存活时间
    • putAllWithTtl

      public void putAllWithTtl(Map<? extends K, ? extends V> map, Duration ttl)
      Description copied from interface: Cache
      Put all entries with custom TTL 批量放入并指定自定义 TTL
      Specified by:
      putAllWithTtl in interface Cache<K,V>
      Parameters:
      map - the key-value pairs | 键值对 Map
      ttl - the time-to-live for all entries | 所有条目的存活时间
    • putIfAbsentWithTtl

      public boolean putIfAbsentWithTtl(K key, V value, Duration ttl)
      Description copied from interface: Cache
      Put if absent with custom TTL 不存在时放入并指定自定义 TTL
      Specified by:
      putIfAbsentWithTtl in interface Cache<K,V>
      Parameters:
      key - the key | 键
      value - the value | 值
      ttl - the time-to-live | 存活时间
      Returns:
      true if put successfully | 成功放入返回 true
    • invalidate

      public void invalidate(K key)
      Description copied from interface: Cache
      Invalidate a single key 使单个键失效
      Specified by:
      invalidate in interface Cache<K,V>
      Parameters:
      key - the key to invalidate | 要失效的键
    • invalidateAll

      public void invalidateAll(Iterable<? extends K> keys)
      Description copied from interface: Cache
      Invalidate multiple keys 批量失效
      Specified by:
      invalidateAll in interface Cache<K,V>
      Parameters:
      keys - the keys to invalidate | 要失效的键集合
    • invalidateAll

      public void invalidateAll()
      Description copied from interface: Cache
      Invalidate all entries 清空所有缓存
      Specified by:
      invalidateAll in interface Cache<K,V>
    • containsKey

      public boolean containsKey(K key)
      Description copied from interface: Cache
      Check if key exists 检查键是否存在
      Specified by:
      containsKey in interface Cache<K,V>
      Parameters:
      key - the key | 键
      Returns:
      true if exists | 存在返回 true
    • size

      public long size()
      Description copied from interface: Cache
      Get exact entry count (may be slow) 获取精确条目数(可能较慢)
      Specified by:
      size in interface Cache<K,V>
      Returns:
      entry count | 条目数
    • estimatedSize

      public long estimatedSize()
      Description copied from interface: Cache
      Get estimated entry count (fast) 获取估算条目数(快速)
      Specified by:
      estimatedSize in interface Cache<K,V>
      Returns:
      estimated count | 估算数量
    • keys

      public Set<K> keys()
      Description copied from interface: Cache
      Get snapshot of all keys 获取所有键的快照
      Specified by:
      keys in interface Cache<K,V>
      Returns:
      set of keys | 键集合
    • values

      public Collection<V> values()
      Description copied from interface: Cache
      Get snapshot of all values 获取所有值的快照
      Specified by:
      values in interface Cache<K,V>
      Returns:
      collection of values | 值集合
    • entries

      public Set<Map.Entry<K,V>> entries()
      Description copied from interface: Cache
      Get snapshot of all entries 获取所有条目的快照
      Specified by:
      entries in interface Cache<K,V>
      Returns:
      set of entries | 条目集合
    • asMap

      public ConcurrentMap<K,V> asMap()
      Description copied from interface: Cache
      Get a concurrent map view of this cache 获取 ConcurrentMap 视图
      Specified by:
      asMap in interface Cache<K,V>
      Returns:
      concurrent map view | ConcurrentMap 视图
    • stats

      public CacheStats stats()
      Description copied from interface: Cache
      Get cache statistics 获取缓存统计信息
      Specified by:
      stats in interface Cache<K,V>
      Returns:
      cache statistics | 缓存统计
    • metrics

      public CacheMetrics metrics()
      Description copied from interface: Cache
      Get detailed cache metrics with latency percentiles 获取带延迟百分位数的详细缓存指标
      Specified by:
      metrics in interface Cache<K,V>
      Returns:
      cache metrics or null if not enabled | 缓存指标,未启用则返回 null
    • cleanUp

      public void cleanUp()
      Description copied from interface: Cache
      Perform cleanup (expired entries, etc.) 执行清理(过期条目等)
      Specified by:
      cleanUp in interface Cache<K,V>
    • async

      public AsyncCache<K,V> async()
      Description copied from interface: Cache
      Get async view of this cache 获取异步视图
      Specified by:
      async in interface Cache<K,V>
      Returns:
      async cache view | 异步缓存视图
    • name

      public String name()
      Description copied from interface: Cache
      Get cache name 获取缓存名称
      Specified by:
      name in interface Cache<K,V>
      Returns:
      cache name | 缓存名称
    • levelCount

      public int levelCount()
      Get number of cache levels 获取缓存级别数
      Returns:
      level count | 级别数
    • getLevel

      public Cache<K,V> getLevel(int level)
      Get cache at specific level 获取特定级别的缓存
      Parameters:
      level - level index (0-based) | 级别索引(从 0 开始)
      Returns:
      cache at level | 该级别的缓存
    • getLevelMetrics

      public List<MultiLevelCache.LevelMetrics> getLevelMetrics()
      Get metrics for all levels 获取所有级别的指标
      Returns:
      list of level metrics | 级别指标列表
    • getMultiLevelStats

      public MultiLevelCache.MultiLevelStats getMultiLevelStats()
      Get aggregate statistics 获取聚合统计
      Returns:
      aggregate stats | 聚合统计