java如何清除缓存
清除 Java 缓存的方法
清除浏览器缓存
使用 java.net.URLConnection 或第三方库(如 Apache HttpClient)发送 HTTP 请求时,可以通过设置请求头禁用缓存:
URLConnection connection = new URL("http://example.com").openConnection();
connection.setRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate");
connection.setRequestProperty("Pragma", "no-cache");
connection.setRequestProperty("Expires", "0");
清除 JVM 缓存
对于 JVM 内存中的缓存(如 SoftReference 或 WeakReference),可以通过强制垃圾回收清除:
System.gc();
但需注意,System.gc() 只是建议 JVM 执行垃圾回收,不保证立即生效。
清除文件系统缓存
如果缓存数据存储在文件中,可以通过删除文件或目录清除:
Path cacheDir = Paths.get("/path/to/cache");
Files.walk(cacheDir)
.sorted(Comparator.reverseOrder())
.forEach(path -> {
try {
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
});
清除第三方缓存库
对于 Ehcache、Guava Cache 或 Caffeine 等库,通常提供明确的清除方法:

-
Ehcache:
CacheManager cacheManager = CacheManager.newInstance(); cacheManager.clearAll(); -
Guava Cache:
Cache<String, String> cache = CacheBuilder.newBuilder().build(); cache.invalidateAll(); -
Caffeine:

Cache<String, String> cache = Caffeine.newBuilder().build(); cache.invalidateAll();
清除 HTTP 客户端缓存
使用 OkHttp 或 Apache HttpClient 时,可以关闭缓存或手动清除:
-
OkHttp:
OkHttpClient client = new OkHttpClient.Builder() .cache(null) // 禁用缓存 .build(); -
Apache HttpClient:
CacheConfig cacheConfig = CacheConfig.custom() .setMaxCacheEntries(0) // 禁用缓存 .build(); CloseableHttpClient client = HttpClients.custom() .setCacheConfig(cacheConfig) .build();
注意事项
- 清除缓存可能导致性能下降或数据丢失,需谨慎操作。
- 对于分布式缓存(如 Redis、Memcached),需调用对应的清除命令或 API。
- 部分缓存框架支持定时自动清除(如 TTL 设置),无需手动干预。






