在 Ehcache 2 中,可以使用 calculateInMemorySize() 获取内存中的大小,例如:
CacheManager manager = CacheManager.create();
Cache cache = new Cache(
new CacheConfiguration("test", 100)
.eternal(true)
.statistics(true));
manager.addCache(cache);
assertEquals(0, cache.calculateInMemorySize());
cache.put(new Element(0, "A"));
cache.put(new Element(1, "B"));
cache.put(new Element(2, "C"));
assertTrue(cache.calculateInMemorySize() > 0);
manager.shutdown();
Ehcache 3.6.1 中的等价物是什么?
在下面,getOccupiedByteSize() 方法返回 -1:
StatisticsService statisticsService = new DefaultStatisticsService();
CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder()
.using(statisticsService)
.build(true);
CacheConfiguration<Integer, String> config =
CacheConfigurationBuilder.newCacheConfigurationBuilder(
Integer.class, String.class, ResourcePoolsBuilder.heap(100))
.withExpiry(ExpiryPolicy.NO_EXPIRY)
.build();
Cache<Integer, String> cache = manager.createCache("test", config);
cache.put(0, "A");
cache.put(1, "B");
cache.put(2, "C");
CacheStatistics stats = statisticsService.getCacheStatistics("test");
TierStatistics heap = stats.getTierStatistics().get("OnHeap");
assertTrue(heap.getOccupiedByteSize() > 0);
manager.close();
它确实适用于内存单元有限的缓存。例如,当缓存配置为:
CacheConfiguration<Integer, String> config =
CacheConfigurationBuilder.newCacheConfigurationBuilder(
Integer.class, String.class,
ResourcePoolsBuilder.newResourcePoolsBuilder().heap(100, MemoryUnit.MB))
.withExpiry(ExpiryPolicy.NO_EXPIRY).build();
这是不可取的,因为缓存必须配置元素限制,而不是内存限制。
根据下面亨利的回答,可以使用 Sizeof.deepSizeOf() 获取内存大小,但是需要一些缓存实现知识来排除不需要的对象,例如:
SizeOfFilter ehcache = new SizeOfFilter() {
@Override
public Collection<Field> filterFields(Class<?> klazz, Collection<Field> fields) {
if (EhcacheBase.class.isAssignableFrom(klazz)) {
for (Field field : fields) {
if ("store".equals(field.getName())) {
return Collections.singletonList(field);
}
}
return Collections.emptyList();
}
return fields;
}
@Override
public boolean filterClass(Class<?> klazz) {
return true;
}
};
SizeOf sizeOf = SizeOf.newInstance(ehcache);
long size = sizeOf.deepSizeOf(cache);
这里有一个增强请求来简化它:https ://github.com/ehcache/ehcache3/issues/2500