Java中如何通过CacheManager获取指定缓存的所有键和值
Spring Cache 获取指定缓存所有键值对的方法
Spring 提供的抽象Cache接口本身没有定义遍历所有键的通用方法,需要根据你使用的底层缓存实现,先获取原生缓存对象再操作,以下是常见实现的处理方案:
1. 底层为Caffeine缓存
import com.github.benmanes.caffeine.cache.Cache; // 先获取Cache实例 org.springframework.cache.Cache springCache = cacheManager.getCache("users"); // 转换为Caffeine原生缓存对象 Cache<Object, Object> nativeCache = (Cache<Object, Object>) springCache.getNativeCache(); // 直接获取所有键值对 Map<Object, Object> allKeyValues = nativeCache.asMap(); // 遍历处理 for (Map.Entry<Object, Object> entry : allKeyValues.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); // 你的业务逻辑 }
2. 底层为Redis缓存
import org.springframework.data.redis.cache.RedisCache; // 先获取Cache实例 org.springframework.cache.Cache springCache = cacheManager.getCache("users"); RedisCache redisCache = (RedisCache) springCache; // 扫描当前缓存前缀下的所有键 String keyPrefix = redisCache.getKeyPrefix(); Set<byte[]> rawKeys = redisCache.getConnectionFactory().getConnection().keys((keyPrefix + "*").getBytes()); // 转换为实际键并取值 for (byte[] rawKey : rawKeys) { String fullKey = new String(rawKey); Object key = fullKey.replace(keyPrefix, ""); Object value = springCache.get(key).get(); // 你的业务逻辑 }
注意:Redis的
keys命令在缓存数据量大时会阻塞主线程,生产环境建议改用scan命令分批遍历。
3. 底层为EhCache 2.x
import net.sf.ehcache.Ehcache; // 先获取Cache实例 org.springframework.cache.Cache springCache = cacheManager.getCache("users"); Ehcache nativeCache = (Ehcache) springCache.getNativeCache(); // 获取所有键 List<Object> allKeys = nativeCache.getKeys(); // 遍历取值 for (Object key : allKeys) { Object value = nativeCache.get(key).getObjectValue(); // 你的业务逻辑 }
通用注意事项
- 全量遍历缓存属于重开销操作,缓存数据量大时会严重影响性能,非必要不建议频繁调用
- 如果业务侧有频繁查询全量缓存的需求,建议单独维护一份键的索引集合,避免全量扫描缓存
内容的提问来源于stack exchange,提问作者Umut
相关产品推荐
相关产品推荐

