java 如何清空缓存
清空 Java 缓存的方法
Java 中的缓存可能涉及多种场景,包括 HTTP 响应缓存、JVM 内存缓存或第三方缓存库(如 Ehcache、Guava Cache)。以下是常见的清空缓存方法:
HTTP 响应缓存清理
若使用 java.net.HttpURLConnection 或 java.net.URLConnection,可通过设置请求头禁用缓存:
URLConnection connection = url.openConnection();
connection.setRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate");
connection.setRequestProperty("Pragma", "no-cache");
connection.setRequestProperty("Expires", "0");
对于 Servlet 响应,设置响应头:
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
JVM 内存缓存清理
手动清空基于 Map 的简单缓存:

Map<String, Object> cache = new HashMap<>();
cache.clear(); // 清空所有条目
第三方缓存库清理
Ehcache 清空缓存示例:
CacheManager cacheManager = CacheManager.getInstance();
Cache cache = cacheManager.getCache("cacheName");
cache.removeAll(); // 清空指定缓存
cacheManager.removalAll(); // 清空所有缓存
Guava Cache 清空缓存示例:

Cache<String, Object> cache = CacheBuilder.newBuilder().build();
cache.invalidateAll(); // 清空所有条目
Caffeine Cache 清空缓存示例:
Cache<String, Object> cache = Caffeine.newBuilder().build();
cache.invalidateAll(); // 清空所有条目
浏览器缓存清理(Java Web 场景)
通过响应头强制浏览器忽略缓存:
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
文件系统缓存清理
使用 File 类删除缓存文件:
File cacheDir = new File("/path/to/cache");
if (cacheDir.exists()) {
File[] files = cacheDir.listFiles();
if (files != null) {
for (File file : files) {
file.delete();
}
}
}
注意事项
- 清空缓存可能导致性能暂时下降,因后续请求需重新加载数据。
- 分布式环境中需同步各节点的缓存状态。
- 部分缓存框架提供定时自动清理策略(如 TTL 配置)。






