Class CacheUtil

java.lang.Object
cloud.opencode.base.cache.util.CacheUtil

public final class CacheUtil extends Object
Cache Utility Class - Helper methods for cache operations 缓存工具类 - 缓存操作的辅助方法

Provides utility methods for key generation, cache warming, and statistics formatting.

提供键生成、缓存预热和统计格式化的工具方法。

Features | 主要功能:

  • Key generation (simple, hash) - 键生成(简单、哈希)
  • Cache warming (sync, async) - 缓存预热(同步、异步)
  • Statistics formatting and comparison - 统计格式化和比较

Usage Examples | 使用示例:

// Generate cache key - 生成缓存键
String key = CacheUtil.key("user", userId, tenantId);

// Warm up cache - 预热缓存
CacheUtil.warmUp(cache, dataMap);

// Format statistics - 格式化统计
String stats = CacheUtil.formatStats(cache.stats());

Security | 安全性:

  • Thread-safe: Yes (stateless) - 线程安全: 是(无状态)
  • Null-safe: Partial - 空值安全: 部分

Performance | 性能特性:

  • Time complexity: key()/hashKey() O(p) where p is the number of key parts; warmUp O(n) where n is the number of entries; formatStats O(1) - 时间复杂度: key()/hashKey() 为 O(p),p为键部分数量;warmUp 为 O(n),n为条目数量;formatStats 为 O(1)
  • Space complexity: O(1) auxiliary space per operation - 空间复杂度: 每次操作辅助空间 O(1)
Since:
JDK 25, opencode-base-cache V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • key

      public static String key(String prefix, Object... parts)
      Generate simple cache key with separator 生成带分隔符的简单缓存键
      Parameters:
      prefix - prefix string | 前缀
      parts - key parts | 键部分
      Returns:
      generated key | 生成的键
    • hashKey

      public static String hashKey(String prefix, Object... parts)
      Generate hash-based key to avoid long keys 生成基于哈希的键以避免过长的键
      Parameters:
      prefix - prefix string | 前缀
      parts - key parts | 键部分
      Returns:
      hash-based key | 基于哈希的键
    • batchKeys

      public static String[] batchKeys(String prefix, int count)
      Generate batch keys with index 生成带索引的批量键

      Examples | 示例:

      // Generate keys: user:batch:0, user:batch:1, user:batch:2
      String[] keys = CacheUtil.batchKeys("user:batch", 3);
      
      Parameters:
      prefix - prefix string | 前缀
      count - number of keys to generate | 要生成的键数量
      Returns:
      array of batch keys | 批量键数组
      Since:
      V2.0.1
    • parseKey

      public static String[] parseKey(String key)
      Parse a composite key into its parts 将复合键解析为各部分

      Examples | 示例:

      String[] parts = CacheUtil.parseKey("user:1001:tenant:abc");
      // Result: ["user", "1001", "tenant", "abc"]
      
      Parameters:
      key - the composite key | 复合键
      Returns:
      array of key parts | 键部分数组
      Since:
      V2.0.1
    • extractPrefix

      public static String extractPrefix(String key)
      Extract prefix from a composite key 从复合键中提取前缀
      Parameters:
      key - the composite key | 复合键
      Returns:
      the prefix (first part) | 前缀(第一部分)
      Since:
      V2.0.1
    • extractSuffix

      public static String extractSuffix(String key)
      Extract suffix from a composite key 从复合键中提取后缀
      Parameters:
      key - the composite key | 复合键
      Returns:
      the suffix (after first colon) | 后缀(第一个冒号之后)
      Since:
      V2.0.1
    • warmUp

      public static <K,V> void warmUp(Cache<K,V> cache, Map<K,V> data)
      Warm up cache with data 使用数据预热缓存
      Type Parameters:
      K - key type | 键类型
      V - value type | 值类型
      Parameters:
      cache - the cache | 缓存
      data - data to load | 要加载的数据
    • warmUpAsync

      public static <K,V> CompletableFuture<Void> warmUpAsync(AsyncCache<K,V> cache, Map<K,V> data)
      Async warm up cache with data 异步使用数据预热缓存
      Type Parameters:
      K - key type | 键类型
      V - value type | 值类型
      Parameters:
      cache - the async cache | 异步缓存
      data - data to load | 要加载的数据
      Returns:
      completion future | 完成 Future
    • formatStats

      public static String formatStats(CacheStats stats)
      Format cache statistics 格式化缓存统计
      Parameters:
      stats - the statistics | 统计
      Returns:
      formatted string | 格式化字符串
    • compareStats

      public static String compareStats(CacheStats before, CacheStats after)
      Compare two statistics snapshots 比较两个统计快照
      Parameters:
      before - statistics before | 之前的统计
      after - statistics after | 之后的统计
      Returns:
      formatted delta string | 格式化的增量字符串
    • formatStatsJson

      public static String formatStatsJson(CacheStats stats)
      Format statistics as JSON-like string 格式化统计为类 JSON 字符串
      Parameters:
      stats - the statistics | 统计
      Returns:
      JSON-like string | 类 JSON 字符串
    • optimalCacheSize

      public static long optimalCacheSize(long memoryMB, long avgEntrySizeBytes)
      Calculate optimal cache size based on memory 基于内存计算最优缓存大小
      Parameters:
      memoryMB - available memory in MB | 可用内存(MB)
      avgEntrySizeBytes - average entry size in bytes | 平均条目大小(字节)
      Returns:
      optimal cache size | 最优缓存大小
    • calculateTtl

      public static long calculateTtl(long maxStalenessSeconds, long updateFrequencySeconds)
      Calculate TTL based on data freshness requirements 基于数据新鲜度要求计算 TTL
      Parameters:
      maxStalenessSeconds - max acceptable staleness in seconds | 最大可接受过期秒数
      updateFrequencySeconds - expected update frequency in seconds | 预期更新频率秒数
      Returns:
      recommended TTL in seconds | 推荐的 TTL 秒数