Class TaggedCache<K,V>

java.lang.Object
cloud.opencode.base.cache.TaggedCache<K,V>
Type Parameters:
K - the type of keys | 键类型
V - the type of values | 值类型
All Implemented Interfaces:
Cache<K,V>

public final class TaggedCache<K,V> extends Object implements Cache<K,V>
Tagged Cache - Cache decorator with tag-based batch invalidation 标签缓存 - 支持基于标签批量失效的缓存装饰器

Allows associating cache entries with one or more tags, and invalidating all entries associated with a given tag in a single operation.

允许将缓存条目与一个或多个标签关联,并在单次操作中失效给定标签下的所有条目。

Features | 主要功能:

  • Tag-based batch invalidation - 基于标签的批量失效
  • Multi-tag support per entry - 每个条目支持多标签
  • Bidirectional tag-key index - 双向标签-键索引
  • Automatic index cleanup on invalidation - 失效时自动清理索引
  • Thread-safe concurrent operations - 线程安全的并发操作

Usage Examples | 使用示例:

// Create tagged cache
Cache<String, String> base = OpenCache.<String, String>builder()
        .maximumSize(1000)
        .build();
TaggedCache<String, String> cache = TaggedCache.wrap(base);

// Put with tags
cache.put("user:1", "Alice", "role:admin", "dept:eng");
cache.put("user:2", "Bob", "role:user", "dept:eng");
cache.put("user:3", "Carol", "role:admin", "dept:hr");

// Query by tag
Set<String> admins = cache.getKeysByTag("role:admin");  // [user:1, user:3]
Set<String> tags = cache.getTags("user:1");             // [role:admin, dept:eng]

// Invalidate by tag — removes all entries tagged with "dept:eng"
cache.invalidateByTag("dept:eng");  // removes user:1 and user:2

// Invalidate by multiple tags
cache.invalidateByTags("role:admin", "role:user");

Performance | 性能特性:

  • put/get/invalidate: O(1) delegate + O(tags) index maintenance - O(1) 委托 + O(标签数) 索引维护
  • invalidateByTag: O(keys in tag) - O(标签下的键数)
  • Memory overhead: two ConcurrentHashMap indexes - 内存开销: 两个 ConcurrentHashMap 索引

Security | 安全性:

  • Thread-safe: Yes (ConcurrentHashMap + atomic operations) - 线程安全: 是(ConcurrentHashMap + 原子操作)
  • Null-safe: Rejects null tags - 空值安全: 拒绝 null 标签
Since:
JDK 25, opencode-base-cache V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • wrap

      public static <K,V> TaggedCache<K,V> wrap(Cache<K,V> cache)
      Wrap an existing cache with tag support 用标签支持包装现有缓存
      Type Parameters:
      K - key type | 键类型
      V - value type | 值类型
      Parameters:
      cache - the cache to wrap | 要包装的缓存
      Returns:
      tagged cache decorator | 标签缓存装饰器
    • put

      public void put(K key, V value, String... tags)
      Put a key-value pair with associated tags 放入带标签的键值对
      Parameters:
      key - the key | 键
      value - the value | 值
      tags - the tags to associate | 关联的标签
    • putWithTtl

      public void putWithTtl(K key, V value, Duration ttl, String... tags)
      Put a key-value pair with TTL and associated tags 放入带 TTL 和标签的键值对
      Parameters:
      key - the key | 键
      value - the value | 值
      ttl - the time-to-live | 存活时间
      tags - the tags to associate | 关联的标签
    • addTags

      public void addTags(K key, String... tags)
      Add tags to a key in the tag index 给键追加标签到标签索引

      Tags are always added to the index. If the key is not currently in the cache, stale tag entries will be cleaned up automatically during the next invalidate(K) or invalidateByTag(String) operation.

      标签始终会被添加到索引中。如果键当前不在缓存中,过期的标签条目将在下次 invalidate(K)invalidateByTag(String) 操作时自动清理。

      Parameters:
      key - the key | 键
      tags - the tags to add | 要追加的标签
    • getKeysByTag

      public Set<K> getKeysByTag(String tag)
      Get all keys associated with a tag 获取标签下所有键
      Parameters:
      tag - the tag | 标签
      Returns:
      unmodifiable set of keys, empty if tag not found | 不可变键集合,标签不存在则返回空集
    • getTags

      public Set<String> getTags(K key)
      Get all tags associated with a key 获取键的所有标签
      Parameters:
      key - the key | 键
      Returns:
      unmodifiable set of tags, empty if key has no tags | 不可变标签集合,无标签则返回空集
    • invalidateByTag

      public void invalidateByTag(String tag)
      Invalidate all entries associated with the given tag 按标签批量失效所有关联条目
      Parameters:
      tag - the tag | 标签
    • invalidateByTags

      public void invalidateByTags(String... tags)
      Invalidate all entries associated with any of the given tags 按多个标签批量失效所有关联条目
      Parameters:
      tags - the tags | 标签数组
    • getAllTags

      public Set<String> getAllTags()
      Get all known tags 获取所有已知标签
      Returns:
      unmodifiable set of all tags | 不可变的所有标签集合
    • getTagSize

      public int getTagSize(String tag)
      Get the count of entries associated with a tag 获取标签下的条目数
      Parameters:
      tag - the tag | 标签
      Returns:
      count of entries | 条目数
    • 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 | 缓存名称
    • computeIfPresent

      public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
      Description copied from interface: Cache
      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,则删除条目。

      Specified by:
      computeIfPresent in interface Cache<K,V>
      Parameters:
      key - the key | 键
      remappingFunction - the function to compute new value | 计算新值的函数
      Returns:
      the new value or null if removed/absent | 新值,如果被删除或不存在则返回 null
    • compute

      public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
      Description copied from interface: Cache
      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,则删除条目。

      Specified by:
      compute in interface Cache<K,V>
      Parameters:
      key - the key | 键
      remappingFunction - the function to compute value | 计算值的函数
      Returns:
      the new value or null if removed | 新值,如果被删除则返回 null
    • replace

      public V replace(K key, V value)
      Description copied from interface: Cache
      Replace value only if key is present 仅在键存在时替换值
      Specified by:
      replace in interface Cache<K,V>
      Parameters:
      key - the key | 键
      value - the new value | 新值
      Returns:
      the old value or null if not present | 旧值,不存在则返回 null
    • replace

      public boolean replace(K key, V oldValue, V newValue)
      Description copied from interface: Cache
      Replace value only if current value equals expected value 仅在当前值等于期望值时替换
      Specified by:
      replace in interface Cache<K,V>
      Parameters:
      key - the key | 键
      oldValue - the expected current value | 期望的当前值
      newValue - the new value | 新值
      Returns:
      true if replaced | 替换成功返回 true
    • getAndRemove

      public V getAndRemove(K key)
      Description copied from interface: Cache
      Get value and remove the entry atomically 原子地获取值并删除条目
      Specified by:
      getAndRemove in interface Cache<K,V>
      Parameters:
      key - the key | 键
      Returns:
      the value or null if not present | 值,不存在则返回 null